6. SpringBoot整合Redis
Redis是NoSQL类型的数据库,我们也常称为内存型数据库类型.在SpringBoot中使用Redis非常简单.
6.1 添加包依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
添加依赖后其实就直接可以使用redis了(SpringBoot提供了默认配置,也可以自己配置)
6.2 配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.timeout=1000
spring.redis.lettuce.pool.max-active=10
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-wait=1000
6.3 编写Controller测试
@Controller
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("/set")
@ResponseBody
public String redisStringSet(String key, String value) {
ValueOperations ops = redisTemplate.opsForValue();
ops.set(key, value);
return "OK";
}
}
当执行了上面的代码后,使用Redis客户端可查看到redis中多出了一个记录.但是该记录是编码后的,不方面我们查看.这就需要我们进行相应的配置了.让redis直接以字符串的方式显示我们插入的内容.
@Configuration
public class RedisTemplateConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 自定义的string序列化器和fastjson序列化器
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer