Spring Boot 整合 Redis 实现缓存操作
本文提纲
一、缓存的应用场景
二、更新缓存的策略
三、运行 springboot-mybatis-redis 工程案例
四、springboot-mybatis-redis 工程代码配置详解
运行环境:
Mac OS 10.12.x
JDK 8 +
Redis 3.2.8
Spring Boot 1.5.1.RELEASE
1、springboot-mybatis-redis 工程代码配置详解
1、 pom.xml 依赖配置:
<!-- Spring Boot Reids 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>${spring-boot-starter-redis-version}</version>
</dependency>
2、 在 application.properties 应用配置文件,增加 Redis 相关配置
## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
## 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
## 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=0
详细解释可以参考注释。对应的配置类:org.springframework.boot.autoconfigure.data.redis.RedisProperties
CityRestController 控制层依旧是 Restful 风格的,详情可以参考《Springboot 实现 Restful 服务,基于 HTTP / JSON 传输》。 http://www.bysocket.com/?p=1627 domain 对象 City 必须实现序列化,因为需要将对象序列化后存储到 Redis。如果没实现 Serializable ,控制台会爆出以下异常
如果需要自定义序列化实现,只要实现 RedisSerializer 接口去实现即可,然后在使用 RedisTemplate.setValueSerializer 方法去设置你实现的序列化实现。
3、 代码的实现
/**
* 获取城市逻辑:
* 如果缓存存在,从缓存中获取城市信息
* 如果缓存不存在,从 DB 中获取城市信息,然后插入缓存
*/
public City findCityById(Long id) {
// 从缓存中获取城市信息
String key = "city_" + id;
ValueOperations<String, City> operations = redisTemplate.opsForValue();
// 缓存存在
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
City city = operations.get(key);
LOGGER.info("CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + city.toString());
return city;
}
// 从 DB 中获取城市信息
City city = cityDao.findById(id);
// 插入缓存
operations.set(key, city, 10, TimeUnit.SECONDS);
LOGGER.info("CityServiceImpl.findCityById() : 城市插入缓存 >> " + city.toString());
return city;
}
关于修改springboot中redis配置中的修改RedisTemplate 默认的序列化规则(修改成JSON数据类型)
原理:覆盖默认配置类;
在创建的springboot项目中的启动类中:
public static void main(String[] args) {
SpringApplication.run(TestspringBoot04redisApplication.class, args);
}
//覆盖默认的自动配置
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//修改默认的序列化规则
//1.创建序列化规则对象
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
//2.更改默认的序列化规则
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}