原因: RedisTemplate 默認使用:JdkSerializationRedisSerializer 序列化。
解決方案:
@Autowired
RedisTemplate redisTemplate;
修改為:
@Autowired
StringRedisTemplate stringRedisTemplate;
拓展:
1.SpringBoot 項目使用 Redis:
①`pom.xml` 添加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
②配置`application.properties` :
#Redis服務器地址
spring.redis.host=127.0.0.1
#Redis服務器連接端口
spring.redis.port=6379
#Redis服務器連接密碼(默認為空)
spring.redis.password=123456
spring.redis.database=0
#連接池最大連接數(shù)(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=8
#連接池中的最大空閑連接
spring.redis.jedis.pool.max-idle=8
#連接池中的最小空閑連接
spring.redis.jedis.pool.min-idle=3
#連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1ms
#連接超時時間(毫秒)
spring.redis.timeout=30000
③注入,使用:
@Autowired
StringRedisTemplate stringRedisTemplate;
stringRedisTemplate.opsForValue().set("key", "value");
String value = stringRedisTemplate.opsForValue().get("key");
System.out.println(value);
stringRedisTemplate.opsForHash().entries("hash")
2.SpringBoot 項目使用 Redis,切換 Database 方法:
LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) stringRedisTemplate.getConnectionFactory();
if (connectionFactory != null) {
connectionFactory.setDatabase(16);
stringRedisTemplate.setConnectionFactory(connectionFactory);
//connectionFactory.resetConnection(); //很多資料中執(zhí)行 resetConnection() 方法,不起作用
connectionFactory.afterPropertiesSet(); //使用 afterPropertiesSet() 能正常切換
}
注:SpringBoot 版本:2.2.8.RELEASE。