Spring Cache Redis结合遇到的坑

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

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

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.代码中使用spa

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

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

缘由: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 typeblog

解决:坑了个爹了,基类的方法是protected类型的,改为public就能够了get

相关文章
相关标签/搜索