添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
添加yml配置
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
password:
timeout: 1000
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
luttuce:
shutdown-timeout: 0
使用
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void setRedisValue() {
char[] a = new char[2*1024];
String s = JSON.toJSONString(a);
redisTemplate.opsForValue().set("user", s);
}
序列化
默认的redis序列化为StringRedisSerializer,value只能设置string字符串,如果想保存对象,需要设置序列化方法。
@Configuration
public class RedisConfiguration {
@Bean()
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
{
RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(stringRedisSerializer);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
使用
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
public void setRedisValue() {
User user = new User();
user.name = "spring";
user.age = 18;
redisTemplate.opsForValue().set("user", user);
}
private class User
{
private String name;
private int age;
}