Spring Cache Redis结合遇到的坑

业务上需要把一些数据放到redis里面,但是系统逻辑代码差不多编写完成了,怎么整?用Spring Cache啊,对既有业务逻辑侵袭极小。

于是尝试调查了一下,遇到一些问题分享一下(本文使用Spring MVC,不使用Spring Boot)

1.配置:

<!--启用缓存-->
    <cache:annotation-driven cache-manager="cacheManager"/>
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">    
         <property name="caches">    
            <set>    
                <!-- 这里可以配置多个redis -->  
                <bean class="com.xxx.cache.RedisCache">    
                     <property name="redisTemplate" ref="redisTemplate" />    
                     <property name="name" value="yyy"/>    
                     <!-- name对应的名称要在类或方法的注解中使用 可以指定多个cache管理模式 -->  
                </bean>  
            </set>    
         </property>    
     </bean>    

2.代码中使用

@Cacheable(value="yyy",key="#root.target.getCompanyID()+#xxxId")
    public List<XXXInfo> getXXXData(int xxxId) {

3.遇到的坑1:Cache机制不被触发

原因:getXXXData()是个内部方法,在同一个Service1的另外一个方法中被内部调用,不是直接被Controller调用的。
解决:在同一个Service1中,自注入(Self autowiring),这货好像Spring4.3之前还不支持
@Autowired
Service1 self

// 调用的地方
self.getXXXData(xxxId);

 4.遇到的坑2:Key上面的SpEL表达式使用了基类的方法getCompanyID(),报错找不到方法。EL1004E: Method call: Method getCompanyID()  cannot be found on org.springframework.cache.interceptor.CacheExpressionRootObject type

解决:坑了个爹了,基类的方法是protected类型的,改成public就可以了

猜你喜欢

转载自www.cnblogs.com/Amar/p/9209816.html
今日推荐