是否可以使用 Spring 的缓存抽象和 redis 创建多个缓存存储?



我正在使用Spring MVC开发一个web应用程序,并使用Spring的缓存抽象和Redis来缓存我的数据库查询。但是我无法使用@Cacheable创建多个缓存存储。

@Cacheable("acache")
public String atest(int i) {
   return "a";
}
@Cacheable("bcache")
public String btest(int i) {
   return "b";
}
...
...
String s = atest(1);
String r = btest(1);

使用redis,sr都具有相同的值"a"。尽管我将这两个方法缓存在不同的缓存中,但似乎没有任何效果。

但是,当我使用Spring的SimpleCacheManager时,这很好用。

Redis的Spring bean配置:

<cache:annotation-driven />
<bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:hostName="${redis.host-name}"
        p:port="${redis.port}"
        p:usePool="true"/>

<bean id="redisTemplate"
        class="org.springframework.data.redis.core.RedisTemplate"
        p:connectionFactory-ref="jedisConnectionFactory"/>
<bean id="cacheManager"
        class="org.springframework.data.redis.cache.RedisCacheManager"
        c:template-ref="redisTemplate">
</bean>

根据文档,RedisCacheManager默认情况下直接保存密钥,而不添加前缀(缓存名称,用作命名空间)。要更改它并避免冲突,请将"usePrefix"设置为"true":http://static.springsource.org/spring-data/data-redis/docs/current/api/org/springframework/data/redis/cache/RedisCacheManager.html

最新更新