我的 spring boot 项目有以下配置。
@SpringBootApplication
@EnableTransactionManagement
@EnableCaching
@EnableScheduling
@EnableAsync
public class Application {
String redisHost = "localhost";
int redisPort = 6379;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisHost);
factory.setPort(redisPort);
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
@Bean
public CacheManager cacheManager() {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
return cacheManager;
}
}
我也有以下对pom的maven依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
我有一个单独的 redis 服务器在我的本地机器上的定义端口上运行。同样在我的服务类中,我有 @Cacheable、@CachePut 等注释来支持缓存。
我可以毫无错误地启动 Spring Boot 应用程序,并且 CRUD 操作也可以。但似乎它没有使用定义的 redis 缓存。我使用’redi desktop manager’浏览工具,在redis上找不到任何数据。我还尝试通过 redis cli 命令“monitor”监视 redis 服务器,但在监视器上看不到任何更改。
所以我假设redis缓存仍然无法在我的spring boot应用程序上运行。有人可以帮我解决这个问题吗?
我正在使用 Spring Boot 版本 1.4.2.RELEASE
谢谢!
原文由 lsc 发布,翻译遵循 CC BY-SA 4.0 许可协议
鉴于您使用的是 Spring Boot ,您的大部分 Redis 配置都是不必要的,因为 Spring Boot 为 Redis 提供了“ _自动配置_”支持,既可以作为 数据源,也可以作为 缓存提供程序。
您也没有具体说明您正在使用什么版本的 Spring Boot (例如
1.5.0.RC1
)来运行您的应用程序,或者您的应用程序的类路径上是否有任何application.properties
,这可能会使如果您明确指定spring.cache.type
(例如,设置为“redis”以外的其他内容),则会有所不同。但是,总的来说,我真的看不出您的 Redis 或 Spring Cache
@Configuration
类有什么问题。但是,没有明确设置cacheManager.setUsePrefix(true)
似乎确实是个问题。当我设置这个RedisCacheManager
属性(’usePrefix`)时,一切都按预期工作。我不是(Spring Data)Redis 专家,所以我不确定为什么需要这样做。但是,我的测试配置基于 Spring Boot 对 Redis 缓存的“ _自动配置_”支持 以及您的
@Configuration
“应用程序”类,如上所示。而且,因为您可以消除大部分显式配置并使用 Spring Boot 对 Redis 作为数据源的
"AutoRedisConfiguration"
自动配置” 支持,@Configuration
我在我的测试班。即您可以使用它来配置 Redis 而不是我的其他@Configuration
类("CustomRedisConfiguration"
),它使用您的配置 + 修复。这是完整的测试示例…
希望这可以帮助!
干杯,约翰