一、版本
Spring Boot 2.2.2.RELEASE
二、依赖
默认lettuce客户端
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
jedis客户端
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.client</groupId>
<artifactId>jedis</artifactId>
</dependency>
三、配置
配置文件
# redis配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=500
四、测试
代码
@RestController
public class UserController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private UserService userService;
@RequestMapping(value = "/selectUserById", method = RequestMethod.GET)
public User selectUserById(Integer id) {
User user = userService.selectByPrimaryKey(id);
redisTemplate.opsForValue().set("test", user.toString());
return user;
}
}
结果
默认的RedisTemplate<Object,Object>使用JdkSerializationRedisSerializer会得到一些复杂的字符串
自定义RedisTemplate<String,Object>,新增一个RedisConfig配置类,使用StringSerializer序列化key,Jackson2JsonRedisSerializer序列化Value
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
RedisSerializer<String> stringSerializer = redisTemplate.getStringSerializer();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
return redisTemplate;
}
}
结果