Springboot整合redis实现缓存
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置RedisConfig
@EnableCaching
@Configuration
public class RedisConfig {
@Bean
RedisCacheConfiguration redisCacheConfiguration() {
// 读取redis的默认配置模板
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// 设置过期时间
config = config.entryTtl(Duration.ofDays(1));
// 设置KEY的前缀
config.prefixKeysWith("CACHE_");
// 开启使用KEY前缀
config.usePrefix();
// 设置允许缓存空值,防止缓存穿透
config.getAllowCacheNullValues();
// 配置key的序列化方式
config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
// 配置value的序列化方式
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return config;
}
}
RedisTemplate常用方法
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
Redis常用缓存注解
注解名 作用
@Cacheable 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@CacheEvict 清空缓存
@CachePut 保证方法被调用,又希望结果被缓存
@EnableCaching 开启基于注解的缓存
解决缓存穿透、缓存雪崩、缓存击穿
- 空结果缓存:解决缓存穿透问题
- 设置过期时间加随机值:解决缓存雪崩
- 加锁:解决缓存击穿
Redisson整合 可重入锁 读写锁
官网地址 github redisson wiki
导入依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<!--适用于2.2.x版本-->
<version>3.13.1</version>
</dependency>
配置RedissonConfig
@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redisson() {
//1. 创建配置
Config config = new Config();
config.useSingleServer().setAddress("redis://192.168.56.10:6379");
// 2. 根据config创建出RedissonClient实例
RedissonClient redisson = Redisson.create(config);
return redisson;
}
}
可重入锁
RLock rLock = redissonClient.getLock("lock");
rLock.lock();
rLock.unlock();
读写锁
// 读
@GetMapping("read")
public R read() {
RLock lock = redissonClient.getReadWriteLock("rw-lock").readLock();
try {
lock.lock();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return R.ok().data("data", "read");
}
// 写
@GetMapping("write")
public R write() {
RLock lock = redissonClient.getReadWriteLock("rw-lock").writeLock();
try {
lock.lock();
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return R.ok().data("data", "write");
}