springboot整合redis
- 引入redis和SpringCache的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- 在application.properties中指定缓存类型为redis
spring.cache.type=redis
spring.cache.redis.time-to-live=3600000
spring.cache.redis.use-key-prefix=true
#是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true
- 在application.yml中连接redis
spring:
redis:
host: 192.168.56.101
port: 6379
- 编写SpringCache的配置类(默认使用jdk进行序列化(可读性差),默认ttl为-1永不过期,自定义序列化方式需要编写配置类),并在配置类上标注相关注解
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching
@Configuration
public class MyCacheConfig {
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
//指定缓存序列化方式为json
//设置配置文件中的各项配置,如过期时间
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}
- 在业务方法上标注@Cacheable注解
@Cacheable(value = {"voList"}, key = "#root.method.name", sync = true)
@Override
public List<EmployeeVo> getList() {
List<EmployeeEntity> employeeList = employeeDao.selectList(null);
List<EmployeeVo> voList = new ArrayList<>();
if (null != employeeList && employeeList.size() > 0) {
for (EmployeeEntity employee : employeeList) {
EmployeeVo employeeVo = new EmployeeVo();
BeanUtils.copyProperties(employee, employeeVo);
DepartEntity depart = departDao.selectById(employee.getDepid());
employeeVo.setDepname(depart.getDepname());
voList.add(employeeVo);
}
}
return voList;
}
- 调用controller方法测试缓存是否保存在redis中