依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
配置文件
spring.redis.host=127.0.0.1
spring.redis.port=6739
spring.redis.password=
Redis配置类
@Configuration
public class RedisAutoConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private Integer port;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jcf = new JedisConnectionFactory();
jcf.setHostName(host);
jcf.setPort(port);
jcf.setPassword(password);
return jcf;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.afterPropertiesSet();
setSerializer(redisTemplate);
return redisTemplate;
}
private void setSerializer(RedisTemplate<String, String> template) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
测试
@RequestMapping(value = "/redis/string/object", method = RequestMethod.GET)
public void insertStringObject() {
User user = new User();
user.setUserId(1);
user.setUsername("user1");
user.setPassword("password1");
redisTemplate.opsForValue().set("stringKeyObject", user);
}