spring cache

参考资料:
https://docs.spring.io/spring/docs/5.1.5.RELEASE/spring-framework-reference/integration.html#cache
 
spring cache 提供了缓存的一些注解:
1、@Cacheable
(1)condition属性:可以为spEL表达式,只要满足表达式时才进行缓存。
(2)unless属性:和condition不同的是,在方法执行之后才对条件进行判断,满足条件才进行缓存。所以unless可以对result做判断。示例:只有result为true时才进行缓存
@Cacheable(value = "aa", key = "#param", unless = "#result")
    public boolean isTrue(String param) {
        if (param.equals("aaa")) {
            return true;
        }
        else {
            return false;
        }
    }
2、@CachePut
3、@CacheEvict
 
 
spring cacheable和redis集成
1、配置redis集群
2、实现在注解上增加缓存的过期时间
需要实现RedisCacheWriter接口,重写put方法(RedisCacheWriter的默认实现类为DefaultRedisCacheWriter,但该类没有被访问修饰符修饰,默认为default,所以不能跨包访问,需要自己实现RedisCacheWriter接口)
@Override
public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {

    Assert.notNull(name, "Name must not be null!");
    Assert.notNull(key, "Key must not be null!");
    Assert.notNull(value, "Value must not be null!");

    execute(name, connection -> {

        //判断name里面是否设置了过期时间,如果设置了则对key进行缓存,并设置过期时间
        int index = name.lastIndexOf(RedisKeys.REDIS_EXPIRE_TIME_KEY);
        if (index > 0) {
            //取出对应的时间
            String expireString = name.substring(index + 1 + RedisKeys.REDIS_EXPIRE_TIME_KEY.length());
            long expireTime = Long.parseLong(expireString);
            connection.set(key, value, Expiration.from(expireTime, TimeUnit.SECONDS), RedisStringCommands.SetOption.upsert());
        } else if (shouldExpireWithin(ttl)) {
            connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
        } else {
            connection.set(key, value);
        }
        return "OK";
    });
}

3、配置CacheManager

@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
    return new RedisCacheManager(new RedisCacheWriterCustomer(factory),cacheConfig());
}

其中RedisCacheWriterCustomer为RedisCacheWriter接口的实现类

spring cache + 服务器缓存(encache)
1、配置ehcache.xml文件
2、配置CacheManager
 
 
 
 
原文地址:https://www.cnblogs.com/BonnieWss/p/11607455.html