当前位置:   article > 正文

Spring Cache_spring cache 缓存 介绍 图

spring cache 缓存 介绍 图

一、自定义 缓存实现

1、缓存类

/**
 * 缓存类
 * @param <T>
 */
public class CacheManager<T> {

    private Map<String,T> cache = new ConcurrentHashMap<String,T>();
    
    /*
     * 缓存取值
     */
    public T getValue(Object key) {
        return cache.get(key);
    }
    
    /*
     * 存、更新缓存
     */
    public void addOrUpdateCache(String key,T value) {
        cache.put(key, value);
    }
    
    /**
     * 根据key删除缓存中的一条记录
     * @param key
     */
    public void evictCache(String key) {
        if(cache.containsKey(key)) {
            cache.remove(key);
        }
    }
    
    /*
     * 清空缓存中的记录
     */
    public void evictCache() {
        cache.clear();
    }
}

2、使用

@Service
public class UserService {

    private CacheManager<UserEntity> cacheManager;
    
    @Autowired
    private StudentRepository studentRepository;
    
    public UserService() {
        cacheManager = new CacheManager<UserEntity>();
    }
    
    public UserEntity findByID(Long id) {
        UserEntity user = cacheManager.getValue(id.toString());
        if(user != null) {
            System.out.println("缓存中取值...");
            return user;
        }
        Optional<UserEntity> userEntitys = studentRepository.findById(id);
        user = userEntitys.get();
        if(user != null) {
            System.out.println("走查询了...");
            cacheManager.addOrUpdateCache(id.toString(), user);
        }
        
        return user;
    }
}

二、Spring Cache

1、@Cacheable缓存注解

注解可定义 在类和方法上,一般 标注在方法上 < 只有 public 方法的注解可被缓存>。

缓存键生成规则:

2、@CachePut注解

3、@CacheEvict注解

4、组注解

三、缓存管理器

Eacache 的配置

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.8.2</version>
</dependency>

基于注解的缓存管理器配置:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/785256
推荐阅读
相关标签
  

闽ICP备14008679号