Spring cache + redis 使用手册

2018-11-12  本文已影响0人  丑男李狗蛋

<font style="font-size:1.3em;font-weight:bold;"> 目录 </font>

[toc]

一. 集成

第一步. 添加pom依赖

<dependency>  
   <groupId>org.springframework.data</groupId>  
   <artifactId>spring-data-redis</artifactId>  
   <version>1.6.0.RELEASE</version>  
</dependency> 

第二步. 加入配置文件

1.配置文件
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {

    /**
     * 缓存管理器
     * @param redisTemplate
     * @return
     */
    @Bean(name = "simpleCacheManager")
    @Autowired
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
    
            RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
            //默认缓存失效时间(单位:秒)
            cacheManager.setDefaultExpiration(24*60*60);

        
    }
    
    ....
    
}
2.CacheManager常用参数

二. 缓存缓存注解

1. @Cacheable

1.1 使用场景

最常用的注解,将注解方法的返回值缓存。

工作原理是:首先在缓存中查找,如果没有执行方法并缓存结果,然后返回数据。此注解的缓存名必须指定

示例:

    @Override
    @Cacheable(value = "searchGoodByCondition",key = "#bossUserId + ''")
    public Good searchGoodByCondition(Integer bossUserId) {
        ...
    }
    ...
1.2 常用参数
1.3 默认生成策略

默认的key生成策略是通过KeyGenerator生成的,其默认策略如下:

2. @CacheEvict

2.1 使用场景

常用注解,将@Cacheable缓存清除

示例:

    @Override
    @CacheEvict(cacheNames = {"searchGoodByCondition"},cacheManager = "simpleCacheManager",key = "#good.bossUserId")
    public Good updateGood(Good good) {
        ...
    }
    ...
2.2 常用参数

3. @CachePut

3.1 使用场景

常用注解,用于在update和insert场景,在更新/添加之后,更新缓存值

示例:

    @Override
    @CachePut(cacheNames = {"searchGoodByCondition"},cacheManager = "simpleCacheManager",key = "#good.bossUserId")
    public Good updateGood(Good good) {
        ...
    }
    ...
3.1 常用参数

@Cacheable注解常用参数一致

4. @Caching

4.1 使用场景

用于多种普通注解组合,因为同一个方法只能使用一个相同注解,为了解决这个问题,引入了@caching注解

示例:

    @Caching(evict = {
            @CacheEvict(value = "queryMasterOrderDetail", key = "'queryMasterOrderDetail~'+ #orderNum", cacheManager = "shortCacheManager"),
            @CacheEvict(value = "queryCustomerBuildingAccountByOrderNum", key = "'queryCustomerBuildingAccountByOrderNum~' + #orderNum")
    })
    public Integer deleteOrderAccount(Long orderNum) {
        ...
    }
4.2 常用参数

三. SpEL表达式

1. 基础

名字 位置 描述 示例
methodName root对象 当前被调用的方法名 #root.methodName
method root对象 当前被调用的方法 #root.method
target root对象 当前被调用的目标对象 #root.target
targetClass root对象 当前被调用的目标对象类 #root.targetClass
args root对象 当前被调用的方法的参数列表 #root.args
caches root对象 当前方法调用使用的缓存列表(如@Cacheable(value={"cache1", "cache2"})),则有两个cache #root.caches
参数名称 执行上下文 当前被调用的方法的参数,如findById(Long id),我们可以通过#id拿到参数 #id/#user.id
result 执行上下文 方法执行后的返回值(仅当方法执行之后的判断有效,如‘unless’,'cache evict'的beforeInvocation=false) #result

2. 进阶

2.1 调用静态方法

T(org.springframework.util.ObjectUtils).isEmpty(#orderNum)
    @CacheEvict(value = "queryCustomerBuildingAccountByOrderNum", key = "'queryCustomerBuildingAccountByOrderNum~' + #orderNum",condition="T(org.springframework.util.ObjectUtils).isEmpty(#orderNum)")
    public Integer deleteOrderAccount(Long orderNum) {
        ...
    }

2.2 正则匹配

    @CacheEvict(value = "queryCustomerBuildingAccountByOrderNum", key = "'queryCustomerBuildingAccountByOrderNum~' + #orderNum",condition="#orderNum match '\d{6}'")
    public Integer deleteOrderAccount(Long orderNum) {
        ...
    }

四.常见问题

1.异常处理

redis异常不能导致正常程序无法访问所以需要捕获redis异常,并放行,所以需要对异常进行处理

重写CachingConfigurerSupport类的errorHandler接口

@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
    此处省略一万字...

    /**
     * redis数据操作异常处理 这里的处理:在日志中打印出错误信息,但是放行
     * 保证redis服务器出现连接等问题的时候不影响程序的正常运行,使得能够出问题时不用缓存
     *
     * @return
     */
    @Bean
    @Override
    public CacheErrorHandler errorHandler() {
        CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {

            @Override
            public void handleCachePutError(RuntimeException exception, Cache cache,
                    Object key, Object value) {
                RedisErrorException(exception, key);
            }

            @Override
            public void handleCacheGetError(RuntimeException exception, Cache cache,
                    Object key) {
                RedisErrorException(exception, key);
            }

            @Override
            public void handleCacheEvictError(RuntimeException exception, Cache cache,
                    Object key) {
                RedisErrorException(exception, key);
            }

            @Override
            public void handleCacheClearError(RuntimeException exception, Cache cache) {
                RedisErrorException(exception, null);
            }
        };
        return cacheErrorHandler;
    }

    protected void RedisErrorException(Exception exception,Object key){
        logger.error("redis异常:key=[{}]", key, exception);
    }
    此处省略两万字...
}

2.异常处理类不能处理的异常

2.1 返回值强制转换的异常
    java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

默认情况下,redis使用Jackson进行反序列化json,但是json不能告诉Jackson,这个数字是int还是long,所以当数字在小于Integer.MAX_INT时候,Jackson默认将数字序列化成int类型,当int类型数字注入Long型对象则会出现这个错误

上一篇 下一篇

猜你喜欢

热点阅读