我的 spring 启动项目有以下配置 .
@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;
}
}
我也跟随maven对pom的依赖 .
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
我在定义端口上的本地计算机上运行了一个单独的redis服务器 . 同样在我的服务类中,我有@Cacheable,@ CachePut等注释来支持缓存 .
我可以毫无错误地启动Spring启动应用程序,CRUD操作也可以 . 但似乎它没有使用定义的redis缓存 . 我使用'redi desktop manger'浏览工具,但在redis上找不到任何数据 . 我也尝试通过redis cli命令'monitor'监控redis服务器,我在监视器上看不到任何变化 .
所以我认为redis缓存仍然无法在我的spring启动应用程序上运行 . 有人能帮我解决问题吗?
我使用的是 Spring 季启动版1.4.2.RELEASE
谢谢!
1 回答
鉴于您使用的是Spring Boot,因此大部分Redis配置都是不必要的,因为Spring Boot为Redis提供了“自动配置”支持,无论是data source还是caching provider .
您还没有具体说明您使用的是什么版本的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的"auto-configuration" support for Redis caching以及
@Configuration
"Application"类,如上所示 .而且,因为您可以消除大部分显式配置并使用Spring Boot的"auto-configuration" support for Redis作为数据源,所以我在我的测试类中添加了一个
"AutoRedisConfiguration"
@Configuration
类 . 即您可以使用它来配置Redis而不是我的其他@Configuration
类("CustomRedisConfiguration"
),它使用您的配置 fix .这是完整的测试示例......
希望这可以帮助!
干杯,约翰