zoukankan      html  css  js  c++  java
  • Spring cache 使用说明

    package org.cheng.user.client.service;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.cheng.user.client.entity.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.Cache;
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.CacheConfig;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    
    /**
     * 统一命名缓存 名称
     * @author Cheng
     */
    @CacheConfig(cacheNames = { "user" })
    @Service
    public class UserService {
        
        @Autowired
        private CacheManager cacheManager;
        
        /**
         * 单个命名缓存名称
         * sync 默认为false 为true 需要同步等待
         * @param id
         * @return
         */
        @Cacheable(cacheNames = "user", key = "#id",sync = false)
        public User get(Integer id) {
            System.out.println("--get---");
            User user = new User();
            user.setId(id);
            return user;
        }
    
        /**
         * 按key存储
         * 前置存储条件 condition 为true 存储
         * 后置执行条件 unless  为false 存储
         * 
         * @param user
         * @return
         */
        @CachePut(key = "#user.id", condition = "#user.id<10000", unless = "#result.name.length() < 3")
        public User save(User user) {
            user.setName("name - " + user.getId());
            return user;
        }
    
        /**
         * 按key删除
         * 
         * @param id
         * @return
         */
        @CacheEvict(key = "#id")
        public String del(Integer id) {
            System.out.println("--del---");
            return String.valueOf(id);
        }
    
        /**
         * 清除全部
         */
        @CacheEvict(allEntries = true)
        public void removeAll() {
        }
        
        /**
         * 返回所有的缓存信息
         * @return
         */
        public Map<String,Cache> cache() {
            Map<String,Cache> map = new HashMap<>();
            for(String name:cacheManager.getCacheNames()) {
                map.put(name, cacheManager.getCache(name));
            }
            return map;
        }
    
    }

    参考文献:

    https://docs.spring.io/spring/docs/5.1.6.RELEASE/spring-framework-reference/integration.html#cache

    https://www.cnblogs.com/OnlyCT/p/7845660.html#t4

  • 相关阅读:
    (转)JAVA国际化
    (转)实现这两个接口ModelDriven<T>,Preparable有什么用?
    cordova 与 phonegap关系
    NApache+JBOSS架构方案
    (转)Java 标注(Annotation)详解
    Jboss集群(五)--F5硬件负载均衡器双击热备 + Jboss集群终极实现
    GTK+/GNOME编程(一)
    二维数组中查找指定的数
    计算字符串距离
    统计指定数字的个数,并将其按权值10的次方数相加
  • 原文地址:https://www.cnblogs.com/tusheng/p/10766151.html
Copyright © 2011-2022 走看看