基于注解的配置实现spring Cache本地缓存 操作
spring
Guava
cache
$begin$
接下来就该说说spring中Guava的基于注解的实现的配置
当然 ,这里只说基于注解的配置和使用 我不会去说注解的原理 这不是本文要说的 .
1.首先 新建一个spring-cache.xml配置文件 并将文件配置于web.xml中
- spring-cahe文件配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true"/> <bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager"> <property name="cacheManagers"> <list> <ref bean="guavaCacheManager"/> </list> </property> <property name="fallbackToNoOpCache" value="true"/> </bean> <bean id="guavaCacheManager" class="cn.springmvc.cache.GuavaCacheManagerConfig"> <property name="configMap"> <map key-type="java.lang.String" value-type="com.google.common.cache.CacheBuilder"> <entry key="likr" value-ref="defaultCacheBuilder"/> </map> </property> </bean> <bean id="defaultCacheBuilder" class="com.google.common.cache.CacheBuilder" factory-method="from"> <constructor-arg value="maximumSize=10000, expireAfterWrite=1h"/> </bean>
|
3.GuavaCacheManagerConfig的具体实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public class GuavaCacheManagerConfig extends AbstractTransactionSupportingCacheManager { private final ConcurrentMap<String, Cache> cacheMap = Maps.newConcurrentMap(); private Map<String, CacheBuilder> builderMap = Maps.newHashMap(); @Override protected Collection<? extends Cache> loadCaches() { return cacheMap.values(); } @Override public Cache getCache(String name) { Cache cache = this.cacheMap.get(name); if (null == cache) { synchronized (this.cacheMap) { cache = this.cacheMap.get(name); if (null == cache && this.builderMap.containsKey(name)) { CacheBuilder builder = this.builderMap.get(name); cache = createGuavaCache(name, builder); this.cacheMap.put(name, cache); } } } return cache; } private Cache createGuavaCache(String name, CacheBuilder builder) { com.google.common.cache.Cache<Object, Object> cache; if(builder == null){ cache = CacheBuilder.newBuilder().build(); }else{ cache = builder.build(); } return new GuavaCache(name, cache, isAllowNullValues()); } private boolean isAllowNullValues() { return true; } public void setConfigMap(Map<String, CacheBuilder> configMap) { this.builderMap = configMap; } }
|
4.代码中使用:
1 2 3 4 5 6 7 8 9
| @Override @Cacheable(value = "likr", key = "'selectByRecordOne:userId:' + #record.user_id") public LikrUserQuestionnaire selectByRecordOne(LikrUserQuestionnaire record) { return likrUserQuestionnaireMapper.selectByRecordOne(record); }
|
$end$