@Cacheable配置,redis缓存应用

CacheManager

缓存配置

web.xml配置spring-context.xml启动加载

<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring-context.xmlparam-value>
context-param>

spring-context.xml中导入spring-ecache.xml

<import resource="spring-ecache.xml" />

spring-ecache.xml中配置cache-manager

<cache:annotation-driven cache-manager="redisCacheManager"/>

 
<bean id="redisCacheManager" class="CustomizedRedisCacheManager">
  <constructor-arg ref="redisTemplate"/>
  <property name="defaultExpiration" value="${redis.cache.time} "/>
bean>

缓存要应用的bean

public class CustomizedRedisCacheManager extends RedisCacheManager {

    private Long defaultExpiration;

    public CustomizedRedisCacheManager(RedisOperations redisOperations) {
        super(redisOperations);
    }

    @Override
    public Cache getCache(String name) {
        // 缓存数据默认存放3600s,即1个小时
        if (defaultExpiration == null) {
            defaultExpiration = 3600L;
        }
        super.setDefaultExpiration(defaultExpiration);

        Cache cache = super.getCache(name);
        return cache;
    }

    public Cache getCache(String name, Long expireDate) {
        super.setDefaultExpiration(expireDate);

        Cache cache = super.getCache(name);
        return cache;

    }

    public Long getDefaultExpiration() {
        return defaultExpiration;
    }

    public void setDefaultExpiration(Long defaultExpiration) {
        this.defaultExpiration = defaultExpiration;
    }

}

注解方式,缓存到ConcurrentHashMap,也就是保存到内存

// 参数改变时,缓存会记录,下次查询时会从缓存拿数据,不会再进该方法
@EnableCaching
public class ProjectConfig extends CachingConfigurerSupport {
	@Bean
	@Override
	public CacheManager cacheManager() {
		SimpleCacheManager cacheManager = new SimpleCacheManager();
		cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("fieldSets")));
		return cacheManager;
	}
}

@Cacheable(value = "fieldSets")
public List<Position> getViewFieldSets(String typeId) {
    Type type = MetaLoader.getLoader().loadType(typeId);
    return ((DetailView) type.getView(apiViewName).getView().getDefinition()).getFieldsets().get(0).getItems();
}

你可能感兴趣的:(缓存,redis基础,java,spring,redis,缓存)