welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

spring注解式cache缓存配置


分类 Java   关键字 分享   标签 java   spring   发布 hongwei  1441523974341
注意 转载须保留原文链接,译文链接,作者译者等信息。  
spring提供了基于map的内存缓存,还支持集成第三方缓存实现比如ehcache、redis、memcached等,注解式cache配置可以很方便地为方法加上缓存支持,另外AOP也许能无侵入地为任意方法增加缓存支持。

ehcache配置:适合单机测试运行环境
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
<property name="cacheManagerName" value="ehcache"/>
</bean>
<bean id="springCacheManager" class="com.itecheast.ite.domain.util.MyEhCacheCacheManager">
<property name="cacheManager" ref="ehcacheManager"/>
</bean>

redis配置:适合线上主备运行环境
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWait" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="poolConfig" ref="poolConfig" />
<property name="database" value="${redis.database}" />
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="springCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg ref="redisTemplate" />
<property name="usePrefix" value="true" />
</bean>

注解式支持,@Cacheable、@CacheEvict、@CacheUpdate
<cache:annotation-driven cache-manager="springCacheManager"/>

public class CodeListServiceImpl implements CodeListService {
@Cacheable(value="itemList", key="#type")
public Result<List<CodeList>> list(String type) {}

@Cacheable(value="itemList", key="#type+'-'+#code")
public Result<CodeList> item(String type, String code) {}
}

手动调用缓存服务,完整代码见repos.xlongwei.com
public abstract class BaseServiceImpl<Entity extends BaseEntity> implements BaseService<Entity>, InitializingBean {

@Autowired CacheManager cacheManager;

protected Class<Entity> entityClass;
protected String entityCache, listCache;

public abstract BaseRepository<Entity> getRepository();

@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
entityClass = (Class<Entity>) GenericTypeResolver.resolveTypeArgument(getClass(), BaseService.class);
entityCache = entityClass.getSimpleName()+".entity";
listCache = entityClass.getSimpleName()+".list";
}

@Transactional
public Result<Entity> create(Entity entity) {
Result<Long> nextID = idService.next();
entity.setId(nextID.getObject());
Entity save = getRepository().save(entity);
if(NumberUtil.parseBoolean(GlobalConfig.getProperty("base.cached"), true)) {
cacheManager.getCache(listCache).clear(); //添加行之后清除list缓存
}
return Result.newSuccess(save);
}

@Transactional(readOnly=true)
public Result<Entity> retrieve(Long entityId) {
if(NumberUtil.validateID(entityId)) {
Entity entity = getFromCache(entityCache, String.valueOf(entityId), entityClass); //优先取缓存数据
if(entity == null) {
entity = getRepository().findOne(entityId);
if(entity!=null && NumberUtil.parseBoolean(GlobalConfig.getProperty("base.cached"), true))
cacheManager.getCache(entityCache).put(String.valueOf(entityId), entity); //存入缓存
}
if(entity!=null) return Result.newSuccess(entity);
}
return DomainErrors.Bad_ID(entityId);
}

@SuppressWarnings("unchecked")
private <T> T getFromCache(String name, String key, Class<T> clazz) {
if(NumberUtil.parseBoolean(GlobalConfig.getProperty("base.cached"), true)) {//缓存有总控开关
ValueWrapper valueWrapper = cacheManager.getCache(name).get(key);
if(valueWrapper!=null) {
Object value = valueWrapper.get();
if(value!=null && clazz.isAssignableFrom(value.getClass())) {
logger.info("get from cache: "+name+","+key+","+value);
return (T)value;
}
}
}
return null;
}
}

配置文件,ite.properties
<bean id="propertySourcesPlaceholderConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="location" value="classpath:ite.properties"/>
<property name="fileEncoding" value="UTF-8"/>
</bean>

base.cached=false
##redis缓存配置
redis.host=127.0.0.1
redis.port=6379
redis.database=0
redis.maxIdle=30
redis.maxWait=3000
redis.testOnBorrow=true

参考:spring集成redis缓存