完整demo下载地址:https://download.csdn.net/download/ganjing222/10647902
刚刚才搭建好了springboot 2.03版本+ redis3.2版本 + yml配置文件。发现网上相关与redis有几个坑。
1: spring-boot-starter-data-redis与spring-boot-starter-redis两个包的区别
看到很多网上的文章引入的是spring-boot-starter-redis。但是我在引入这个包时,却发现没有。这个是因为springBoot的版本为1.4.7 以上的时候,spring-boot-starter-redis这个是就不存在了。而对应的是spring-boot-starter-data-redis
2:关于CacheManager cacheManager = new RedisCacheManager(redisTemplate)找不到方法问题。
这个问题主要也是版本问题引起的,new RedisCacheManager(redisTemplate)是版本1.*的方法。new RedisCacheManager(cacheWriter, defaultCacheConfiguration);是2.0的方法.
代码:pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
application-dev.yml
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
timeout: 5000
password:
pool:
max-active: 0
max-wait: -1
max-idle: 8
min-idle: 0
注意:timeout: 别设置为0.,
当设置为0时,可能会报io.lettuce.core.RedisCommandTimeoutException: Command timed out
controller
@RestController
public class HelloController {
@Autowired
private StringRedisTemplate redisTemplate;
@RequestMapping(value = "/demoTest",method = RequestMethod.GET)
public void demoTest(){
redisTemplate.opsForValue().set("test44","test44");
System.out.println(redisTemplate.opsForValue().get("test44"));
}
}