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

相關文章
相關標籤/搜索