首先需自行安装redis数据库
springboot整合redis十分简单,只需要在application配置文件里配置:
spring:
redis:
host: localhost
database: 0
port: 6379
timeout: 3000
即可通过注入redisTemplate操作redis数据库:
@Autowired
RedisTemplate redisTemplate;
@Test
public void set() {
List<String> strList = Arrays.asList("a", "b", "c");
redisTemplate.opsForValue().set("strList", strList);
}
@Test
public void get() {
List<String> strList = (List<String>) redisTemplate.opsForValue().get("strList");
strList.forEach(e -> System.out.println(e));
}
这样就可以使用redis数据库了。但是使用命令行查看数据会有乱码类似"\xac\xed\x00\x05t\x00\astrList"。这是因为使用了默认的序列化。新增fastjson序列化配置RedisTemplate解决乱码。需引入fastjson依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
这个类库有直接支持redis的FastJsonRedisSerializer
@Configuration
public class RedisConfig {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
FastJsonRedisSerializer<Object> fastJsonRedisSerializer =
new FastJsonRedisSerializer<Object>(Object.class);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}