spring cache 實現按照*號刪除快取
spring cache redis的使用過程中,刪除快取只能用具體的key刪除,不能使用萬用字元號,原因是redis不支援del key 這種萬用字元用法,可以通過修改redis原始碼實現,但這種方式修改了redis本身程式碼,後期升級、維護不好操作,具體操作方式可以參見:
git地址:redis-del-with-pattern
我們使用改寫spring-redis cache實現
具體實現方式為:
改寫:org.springframework.data.redis.cache.RedisCache下的evict方法
原為:cacheWriter.remove(name, createAndConvertCacheKey(key));
改為:cacheWriter.clean(name, createAndConvertCacheKey(key));
spring redis最底層是支援了萬用字元的方式的,但是經過包裝後就去掉了
具體在專案中的使用例項如:
在查詢方法上加入快取:
@Override @Cacheable(keyGenerator = "cacheKeyGenerator") public List query(xx x) throws IllegalAccessException { return xxxx; }
其中cacheKeyGenerator生成如
com.demo.service.impl.xxServiceImpl-query-99986a
刪除或更新時:
@Override @CacheEvict(key = "targetClass.name+'-*'") public boolean saveOrUpdate(xx x) { return xxxx; }
其中key時spEL表示式,生成com.demo.service.impl.xxServiceImpl-*
的key
最終效果是在新增或更新時能刪除所有列表的快取key