一、redis缓存
1.1、redission概述
Redisson是架设在Redis基础上的一个Java驻内存数据网格(In-Memory Data Grid)。使得原本作为协调单机多线程并发程序的工具包获得了协调分布式多机多线程并发系统的能力,大大降低了设计和研发大规模分布式系统的难度。它不仅提供了一系列的分布式的Java常用对象,还提供了许多分布式服务。Redisson底层采用的是Netty框架(异步高性能的通信框架,底层采用的是NIO,即非阻塞 IO),Redisson框架提供的几乎所有对象都包含了同步和异步相互匹配的方法。以下是Redisson的结构:
Redisson的github地址
分布式对象:
key相关操作
通用对象桶(RBucket) ✔
二进制流(RBinaryStream)
地理空间对象桶(RGeo)
原子整长形(RAtomicLong)
原子浮点型(RAtomicDouble)
布隆过滤器(RBloomFilter)
基数估计算法(RHyperLogLog)
整长型累加器(RLongAdder )
双精度浮点累加器(RLongDouble )
限流器(RRateLimiter )
分布式集合:
映射(RMap<K, T>)
多映射(RMultimap<K, V>)
【1】基于集(Set)的多值映射(RSetMultimap<K,V>)
【2】基于列表(List)的多值映射(RListMultimap<K, V>)
不重复集(RSet)
有序集(RSortedSet)
计分排序集(RScoredSortedSet)
字典排序集(RLexSortedSet)
列表(RList)
分布式锁和同步器:
可重入锁(RLock )✔
锁(RLock )
联锁(RedissonMultiLock )
红锁(RedissonRedLock )
读写锁(RReadWriteLock )
信号量(RSemaphore)
可过期性信号量(RPermitExpirableSemaphore )
闭锁(RCountDownLatch )
1.2、Spring集成redisson
1.2.1、需要在pom.xml中导入redisson依赖
<!--redisson 依赖-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
</dependency>
1.2.2、编写RedisionConfig类
@Configuration//声明该类为配置类
@Log4j2
@PropertySource(value="classpath:db.properties")//解析properties配置文件
public class RedissonConfig{
//redis连接地址
@Value("${redis.nodes}")
private String nodes;
//获取连接超时时间
@Value("${redis.connectTimeout}")
private int connectTimeout;
//最小空闲连接数
@Value("${redis.connectPollSize}")
private int connectPollSize;
//最小连接数
@Value("${redis.connectionMinimumidleSize}")
private int connectionMinimumidleSize;
//等待数据返回超时时间
@Value("${redis.timeout}")
private int timeout;
//刷新时间
@Value("${redis.retryInterval}")
private int retryInterval;
@Bean(value = "redissonClient",destroyMethod="shutdown")
public RedissonClient config() {
log.info("=====初始化RedissonClient开始======");
String[] nodeList = nodes.split(",");
Config config = new Config();
//单节点
if (nodeList.length == 1) {
config.useSingleServer().setAddress(nodeList[0])
.setConnectTimeout(connectTimeout)
.setConnectionMinimumIdleSize(connectPoolSize)
.setConnectionPoolSize(connectPoolSize)
.setTimeout(timeout);
//集群节点
} else {
config.useClusterServers().addNodeAddress(nodeList)
.setConnectTimeout(connectTimeout)
.setRetryInterval(retryInterval)
.setMasterConnectionMinimumIdleSize(connectionMinimumidleSize)
.setMasterConnectionPoolSize(connectPoolSize)
.setSlaveConnectionMinimumIdleSize(connectionMinimumidleSize)
.setSlaveConnectionPoolSize(connectPoolSize)
.setTimeout(3000);
}
log.info("=====初始化RedissonClient完成======");
return Redisson.create(config);
}
}
1.2.3、在resources下创建db.properties
redis.nodes=redis://127.0.0.1:6379
redis.connectTimeout=5000
redis.connectPoolSize=64
redis.connectionMinimumidleSize=64
redis.maxtotal=500
redis.timeout=4000
redis.retryInterval=1500
context.test=true #测试环境
1.3、缓存穿透
缓存穿透: 缓存穿透是指缓存和数据库中都没有数据,而用户不断发起请求。这个时候用户可能是攻击者,数据库压力倍增,从而导致宕机。
**解决方案:**限制同一个用户在单位时间内对同一个路径的访问频次(次数)
(eg:用户A对路径/b一直在发送请求,而导致服务器一直向数据库查询数据。要解决这个问题可以限制A用户单位时间内对/b的访问次数,也就是对A进行限流操作。)
令牌桶算法: 随着时间流逝,系统会按恒定1/QPS时间间隔(如果QPS=100,则间隔是10ms)往桶里加入Token(想象和漏洞漏水相反,有个水龙头在不断的加水),如果桶已经满了就不再加了,新请求来临时,会各自拿走一个Token,如果没有Token就只能阻塞或者等着下一次发送Token。
令牌桶的另一个好处是可以方便的改变速度,一旦需要提高速率,则按需提高放入桶中的令牌的速率,一般会定时(比如100ms)往桶中增加一定数量的令牌。
基于Redis的分布限流器可以用来在分布式环境下限制请求方的调用频率。既适用于不同Redisson实例下的多线程限流,也适用于相同Redisson实例下的多线程限流。该算法不保证公平性。除了同步接口外,还提供了异步Async、反射式Reactive和RxJava2标准的接口
1.3.1、创建RedisCacheService接口
/**
* @Description: redis数据缓存服务
*/
public interface RedisCacheService {
/**
* 设置是否为多线程的环境
* @param currentTest
*/
void setCurrentTest(boolean currentTest);
/**
* @Description 产生1800到3600秒之间的整数
*/
Integer RandomTime();
/**
* @Description 限流器
* @param key 单位时间内同一个人访问同一个方法同一个key能够访问的次数
* * @return
*/
void tryRateLimiter(String key);
/**
* @Description 缓存单个对象,需要注意的是这里如果之前缓存中有值,则会覆盖
* @param key 格式:业务唯一key
* @return
*/
<T> T addSingleCache(T t, String key);
/**
* @Description 缓存单个对象,需要注意的是这里如果之前缓存中有值,则会覆盖
* @param key 格式:业务唯一key
* @param seconds 超时时间
* @return
*/
<T> T addSingleCache(T t, String key, Long seconds);
/**
* @Description 查询对象:缓存不存在,查询数据,再返回,同时还要放入缓存中
* 注意:缓存时间0.5-1小时之间
* @param singleData 缓存对象
* @return
*/
<T> T singleCache(SingleData<T> singleData, String key);
/**
* @Description 查询对象:缓存不存在,查询数据,再返回,同时还要放入缓存中
* @param singleData 缓存对象
* @return
*/
<T> T singleCache(SingleData<T> singleData, String key, Long seconds);
/**
* @Description 删除singleCache缓存
*/
Boolean deleSingleCache(String key);
/**
* @Description 查询list对象:缓存不存在,查询数据,再返回,同时还要放入缓存中
* 注意:缓存时间0.5-1小时之间
* @param listData 缓存对象
* @return
*/
<T> List<T> listCache(ListData<T> listData, String key);
/**
* @Description 查询list对象:缓存不存在,查询数据,再返回,同时还要放入缓存中
* @param listData 缓存对象
* @return
*/
<T> List<T> listCache(ListData<T> listData, String key, Long seconds);
/**
* @Description 删除list缓存
*/
Boolean deleListCache(String key);
/**
* @Description 查询mapData对象缓存不存在,查询数据,再返回,同时还要放入缓存中
* 注意:缓存时间0.5-1小时之间
* @param mapData 缓存对象
* @return
*/
<K, V> Map<K, V> mapCache(MapData<K, V> mapData, String key);
/**
* @Description mapData对象添加缓存层并指定超时时间:缓存不存在,查询数据,再返回,同时还要放入缓存中
* @param mapData 缓存对象
* @return
*/
<K, V> Map<K, V> mapCache(MapData<K, V> mapData, String key, Long seconds);
/**
* @Description 删除mapCache缓存
*/
Boolean deleMapCache(String key);
}
1.3.2、RedisCacheService的实现类RedisCacheServiceImpl
import com.itheima.travel.basic.ListData;
import com.itheima.travel.basic.MapData;
import com.itheima.travel.basic.SingleData;
import com.itheima.travel.service.RedisCacheService;
import com.itheima.travel.session.*;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.ExceptionsUtil;
import com.itheima.travel.utils.MD5Coder;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* @Description:redis数据缓存服务
*/
@Log4j2
@Service
public class RedisCacheServiceImpl implements RedisCacheService {
//分布式锁后缀
public static final String LOCK_SUFFIX = "_lock";
//默认redis等待时间
public static final int REDIS_WAIT_TIME = 3000;
//默认redis自动释放锁时间
public static final int REDIS_LEASETIME = 1000;
@Autowired
private RedissonClient redissonClient;
//商家的session,用于找到唯一的token
@Autowired
SubjectSellerContext subjectSellerContext;
//用户的session,用于找到唯一的token
@Autowired
SubjectUserContext subjectUserContext;
@Autowired
IpAddrHandler ipAddrHandler;
//兼容多线程测试
boolean isCurrentTest = false;
@Override
public void setCurrentTest(boolean currentTest) {
isCurrentTest = currentTest;
}
//随机生成的缓存存活时间
@Override
public Integer RandomTime(){
int max=3600;
int min=1800;
Random random = new Random();
return random.nextInt(max)%(max-min+1) + min;
}
/**
* 限流器
* @param key 单位时间内同一个人访问同一个方法同一个key能够访问的次数
* 解决了缓存击穿的问题
*
*/
@Override
public void tryRateLimiter(String key) {
//key的值:findRouteById:101010
// 将操作的方法与参数赋值给一个变量,方法名字
String keyHandler = key;
// 区分用户
String token = null;
// 设置访问频次,单位时间内访问的次数
Integer rate = 10;
// 判断当前支持的线程环境
if (!isCurrentTest){
//不是测试环境
// 登录限流
// 获取当前登录的商家信息
SubjectSeller subjectSeller = subjectSellerContext.getSubject();
if (!EmptyUtil.isNullOrEmpty(subjectSeller)){
// 获取商家的token(每一次登录时为本次会话生成的唯一标识)
token = subjectSeller.getToken();
}else {
// 获取用户信息
SubjectUser subjectUser = subjectUserContext.getSubject();
if (!EmptyUtil.isNullOrEmpty(subjectUser)){
// 获取用户的token
token=subjectUser.getToken();
}
}
//如果未登录按IP限流
if (EmptyUtil.isNullOrEmpty(token)){
// 获取请求者的ip地址,并对地址进行加密
// 将加密后的ip作为唯一标识进行限流
token = MD5Coder.md5Encode(ipAddrHandler.requestIpAddr());
/根据ip限流,限制的是一个网段,单位时间内可以访问2000次
rate=2000;
}
}else {
//是测试环境
token = "current_test";
}
//keyHandler的值:findRouteById:101010:sdhfiahkgvjhfdaajvh_rate_limiter
//token:是用户携带的唯一标识
//根据方法名和用户唯一的token生成唯一的令牌
keyHandler = keyHandler+":"+token+"_rate_limiter";
// 初始化 令牌桶对象
RRateLimiter rateLimiter=redissonClient.getRateLimiter(keyHandler);
//设置访问速率
// 参数1: 令牌桶作用范围,全局
// 参数2: 设置单位时间内的访问次数
// 参数3: 设置单位时间
// 参数4: 时间单位
// 在1秒内同一个用户访问同一个路径最多访问10次
// 在1秒内同ip地址访问同一个路径最多访问2000次
rateLimiter.trySetRate(RateType.OVERALL,
rate, 1, RateIntervalUnit.SECONDS);
//从令牌同中获取一个令牌,如果没有令牌则等待下一个令牌桶的生成
rateLimiter.acquire();
}
@Override
public <T> T addSingleCache(T t, String key) {
return addSingleCache(t, key, null);
}
@Override
public <T> T addSingleCache(T t, String key,Long seconds) {
//限流
//key:方法名,对同一个方法对不同的人员限流
this.tryRateLimiter(key);
//创建桶
RBucket<T> bucket = redissonClient.getBucket(key);
bucket.set(t, EmptyUtil.isNullOrEmpty(seconds) ? RandomTime() : seconds,
TimeUnit.SECONDS);
return t;
}
@Override
public <T> T singleCache(SingleData<T> singleData, String key) {
return singleCache(singleData, key,null);
}
@Override
public <T> T singleCache(SingleData<T> singleData, String key, Long seconds) {
//1、限流:为1秒时间内,同一个方法,同一个人,同一个业务key能访问10次
this.tryRateLimiter(key);
//2、构建桶位
RBucket<T> bucket = redissonClient.getBucket(key);
//3、缓存中获得对象
T t = bucket.get();
//4、获得对象为空
if (EmptyUtil.isNullOrEmpty(t)) {
//5、构建锁桶位
RLock lock = redissonClient.getLock(key + LOCK_SUFFIX);
try {
//6、尝试加锁,锁等待时间为10秒,默认释放时间1.5秒
if (lock.tryLock(REDIS_WAIT_TIME,REDIS_LEASETIME,TimeUnit.MILLISECONDS)) {
//7、并发情况下,在10秒内阻塞的线程会再次从缓存中获得对象,最大可能性防止非空返回
t = bucket.get();
if (!EmptyUtil.isNullOrEmpty(t)){
log.info("等待线程:对象返回:{}",t);
return t;
}
try {
log.info("加锁,放过第一个请求");
//8、执行默认方法,查询数据库
t = singleData.getData();
//9、查询出对象,且指定超时时间
if (!EmptyUtil.isNullOrEmpty(t)) {
log.info("放入缓存");
bucket.set(t, EmptyUtil.isNullOrEmpty(seconds) ? RandomTime() : seconds,
TimeUnit.SECONDS);
}
log.info("执行数据查询后返回");
return t;
}catch (Exception e){
//10、如果执行业务体发生异常则返回空对象
log.error("业务执行异常:{}", ExceptionsUtil.getStackTraceAsString(e));
return null;
}finally {
//11、最终释放所有锁,防止缓存的阻塞
log.info("快速释放锁,防止阻塞");
lock.unlock();
}
}else {
//12、并发情况下,等待3秒超时的线程会再次从缓存中获得对象,最大可能性防止非空返回
t = bucket.get();
if (!EmptyUtil.isNullOrEmpty(t)){
log.info("超时线程:对象返回:{}",t);
return t;
}
}
} catch (InterruptedException e) {
//13、拿锁异常抛出,直接返回空,且在1.5秒内自动释放锁
log.info("熔断,直接返回空");
return null;
}
}
//14、缓存对象不为空直接返回
log.info("缓存返回:{}",t);
return t;
}
//删除单例缓存
@Override
public Boolean deleSingleCache(String key) {
//获取redis中的key,value对象
RBucket<Object> bucket = redissonClient.getBucket(key);
if (!EmptyUtil.isNullOrEmpty(bucket)){
return bucket.delete();
}
return true;
}
//添加集合缓存
@Override
public <T> List<T> listCache(ListData<T> listData, String key) {
return listCache(listData, key, null);
}
//添加集合缓存,有超时时间
//加锁解决了缓存击穿的问题
@Override
public <T> List<T> listCache(ListData<T> listData, String key, Long seconds) {
//1、限流:为1秒时间内,同一个方法,同一个人,同一个业务key能访问10次
this.tryRateLimiter(key);
//2、构建桶位
RList<T> list = redissonClient.getList(key);
//3、缓存中获得对象
List<T> t = list.readAll();
//4、获得对象为空
if (EmptyUtil.isNullOrEmpty(t)) {
//5、构建锁桶位
RLock lock = redissonClient.getLock(key + LOCK_SUFFIX);
try {
//6、锁等待时间为3秒,默认释放时间1.5秒
if ( lock.tryLock(REDIS_WAIT_TIME, REDIS_LEASETIME,TimeUnit.MILLISECONDS)) {
//7、并发情况下,在10秒内阻塞的线程会再次从缓存中获得对象,最大可能性防止非空返回
t = list.readAll();
if (!EmptyUtil.isNullOrEmpty(t)){
log.info("等待线程:对象返回:{}",t);
return t;
}
try {
log.info("加锁,放过第一个请求");
//8、执行默认方法,查询数据库
t = listData.getData();
//9、查询出对象,且指定超时时间
if (!EmptyUtil.isNullOrEmpty(t)) {
//将list原来的值删除掉,将新查询出来的结果覆盖上去
list.delete();
list.addAll(t);
list.expire(EmptyUtil.isNullOrEmpty(seconds) ? RandomTime() : seconds,
TimeUnit.SECONDS);
log.info("放入缓存");
}
log.info("执行数据查询后返回");
return list;
}catch (Exception e){
//10、如果执行业务体发生异常则返回空对象
log.error("业务执行异常:{}", ExceptionsUtil.getStackTraceAsString(e));
return null;
}finally {
//11、最终释放所有锁,防止缓存的阻塞
log.info("快速释放锁,防止阻塞");
lock.unlock();
}
}else {
//12、并发情况下,等待3秒超时的线程会再次从缓存中获得对象,最大可能性防止非空返回
t = list.readAll();
if (!EmptyUtil.isNullOrEmpty(t)){
log.info("超时线程:对象返回:{}",t);
return t;
}
}
} catch (InterruptedException e) {
//13、拿锁异常抛出,直接返回空,且在1.5秒内自动释放锁
log.info("熔断,直接返回空");
return null;
}
}
//14、缓存对象不为空直接返回
log.info("缓存返回:{}",t);
return t;
}
@Override
public Boolean deleListCache(String key) {
RList<Object> list = redissonClient.getList(key);
if (!EmptyUtil.isNullOrEmpty(list)){
return list.delete();
}
return true;
}
@Override
public <K, V> Map<K, V> mapCache(MapData<K, V> mapData, String key) {
return mapCache(mapData, key, null);
}
@Override
public <K, V> Map<K, V> mapCache(MapData<K, V> mapData, String key, Long seconds) {
//1、限流:为1秒时间内,同一个方法,同一个人,同一个业务key能访问10次
this.tryRateLimiter(key);
//2、构建桶位
RMapCache<K, V> rMapCache = redissonClient.getMapCache(key);
//3、缓存中获得对象
Map<K, V> map = rMapCache.readAllMap();
//4、获得对象为空
if (EmptyUtil.isNullOrEmpty(map)) {
//5、构建锁桶位
RLock lock = redissonClient.getLock(key + LOCK_SUFFIX);
try {
//6、锁等待时间为10秒,默认释放时间1.5秒
if (lock.tryLock(REDIS_WAIT_TIME, REDIS_LEASETIME,TimeUnit.MILLISECONDS)) {
//7、并发情况下,在10秒内阻塞的线程会再次从缓存中获得对象,最大可能性防止非空返回
map = rMapCache.readAllMap();
if (!EmptyUtil.isNullOrEmpty(map)){
log.info("等待线程:对象返回:{}",map);
return map;
}
try {
log.info("加锁,放过第一个请求");
//8、执行默认方法,查询数据库
map = mapData.getData();
//9、查询出对象,且指定超时时间
if (!EmptyUtil.isNullOrEmpty(map)) {
rMapCache.delete();
rMapCache.putAll(map);
rMapCache.expire(EmptyUtil.isNullOrEmpty(seconds) ? RandomTime() : seconds,
TimeUnit.SECONDS);
log.info("放入缓存");
}
log.info("执行数据查询后返回");
return rMapCache;
}catch (Exception e){
//10、如果执行业务体发生异常则返回空对象
log.error("业务执行异常:{}", ExceptionsUtil.getStackTraceAsString(e));
return null;
}finally {
//11、最终释放所有锁,防止缓存的阻塞
log.info("快速释放锁,防止阻塞");
lock.unlock();
}
}else {
//13、并发情况下,等待3秒超时的线程会再次从缓存中获得对象,最大可能性防止非空返回
map = rMapCache.readAllMap();
if (!EmptyUtil.isNullOrEmpty(map)){
log.info("等待线程:对象返回:{}",map);
return map;
}
}
} catch (InterruptedException e) {
//14、拿锁异常抛出,直接返回空,且在1.5秒内自动释放锁
log.info("熔断,直接返回空");
return null;
}
}
//13、缓存对象不为空直接返回
log.info("缓存返回:{}",map);
return map;
}
@Override
public Boolean deleMapCache(String key) {
RMapCache<Object, Object> mapCache = redissonClient.getMapCache(key);
if (!EmptyUtil.isNullOrEmpty(mapCache)){
return mapCache.delete();
}
return true;
}
}
1.3.3、对其进行测试
@Test
public void TestTryRateLimiter() throws InterruptedException {
//初始化50个线程,让每个线程执行一个请求
ExecutorService executorServicePool = Executors.newFixedThreadPool(50);
//初始化等待数:50
//外部阻塞
CountDownLatch countDownLatch = new CountDownLatch(50);
//内部阻塞
CyclicBarrier cyclicBarrier = new CyclicBarrier(50);
for (int i = 0; i < 50; i++) {
executorServicePool.execute(()-> {
//阻塞
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
log.info("请求线程"+Thread.currentThread().getId()+"时间:{}",new Date());
redisCacheService.tryRateLimiter("tryRateLimiter_101010101");
log.info("处理线程"+Thread.currentThread().getId()+"时间:{}",new Date());
//等待数-1,挂起当前线程
countDownLatch.countDown();
});
}
//等待,计数为0时一次性执行,模拟50个并发
countDownLatch.await();
}
运行结果会发现每秒只处理10个线程,则就对其进行了限流
1.4、缓存击穿
1.4.1、缓存击穿
**缓存击穿:**是指数据库中没有数据,但数据库中有数据(一般指缓存同时到期),这时由于并发用户特别多,同时读缓存没读到数据,又同时去数据库取数据,引起数据库压力倍增,数据库压力过大,导致缓存击穿现象
限制的目标: 不同用户单位时间内对同一个方法的访问频率
解决方案: 加锁(eg:当用户到缓存中查询数据时,缓存中没有数据,这些用户就去数据库中查询,由于用户访问量过多,数据库忙不过来而导致数据库宕机,解决这种问题,对访问的用户进行限制,也就是加锁,用户访问缓存无果去访问数据库时,谁拿到了锁谁进行数据查询,并且redisson有看门狗机制,不用担心死锁的发生。当用户查询出数据后,将数据放入缓存中并释放锁携带数据返回,下一个用户拿到锁之后会先查一遍缓存,如果有数据则释放锁并返回,否则查询数据库。而等待拿锁的用户会有一个超时时间,超过这个时间,用户则返回服务器繁忙等信息,但是在这些等待的用户中,在返回之前会不甘心的再查一遍缓存,如果有数据携带数据返回,否者就返回服务器繁忙。以此防止访问数据库的用户过多造成不不必要的压力,严重形成缓存击穿现象)
1.4.2、解决缓存击穿——>加锁
在解决缓存穿透中已经给出具体的类,这边我就直接上关键代码了
@Override
public <T> List<T> listCache(ListData<T> listData, String key, Long seconds) {
//1、限流:为1秒时间内,同一个方法,同一个人,同一个业务key能访问10次
this.tryRateLimiter(key);
//2、构建桶位
RList<T> list = redissonClient.getList(key);
//3、缓存中获得对象
List<T> t = list.readAll();
//4、获得对象为空
if (EmptyUtil.isNullOrEmpty(t)) {
//5、构建锁桶位
RLock lock = redissonClient.getLock(key + LOCK_SUFFIX);
try {
//6、锁等待时间为3秒,默认释放时间1.5秒
if ( lock.tryLock(REDIS_WAIT_TIME, REDIS_LEASETIME,TimeUnit.MILLISECONDS)) {
//7、并发情况下,在3秒内阻塞的线程会再次从缓存中获得对象,最大可能性防止非空返回
t = list.readAll();
if (!EmptyUtil.isNullOrEmpty(t)){
log.info("等待线程:对象返回:{}",t);
return t;
}
try {
log.info("加锁,放过第一个请求");
//8、执行默认方法,查询数据库
t = listData.getData();
//9、查询出对象,且指定超时时间
if (!EmptyUtil.isNullOrEmpty(t)) {
list.delete();
list.addAll(t);
list.expire(EmptyUtil.isNullOrEmpty(seconds) ? RandomTime() : seconds,
TimeUnit.SECONDS);
log.info("放入缓存");
}
log.info("执行数据查询后返回");
return list;
}catch (Exception e){
//10、如果执行业务体发生异常则返回空对象
log.error("业务执行异常:{}", ExceptionsUtil.getStackTraceAsString(e));
return null;
}finally {
//11、最终释放所有锁,防止缓存的阻塞
log.info("快速释放锁,防止阻塞");
lock.unlock();
}
}else {
//12、并发情况下,等待3秒超时的线程会再次从缓存中获得对象,最大可能性防止非空返回
t = list.readAll();
if (!EmptyUtil.isNullOrEmpty(t)){
log.info("超时线程:对象返回:{}",t);
return t;
}
}
} catch (InterruptedException e) {
//13、拿锁异常抛出,直接返回空,且在1.5秒内自动释放锁
log.info("熔断,直接返回空");
return null;
}
}
//14、缓存对象不为空直接返回
log.info("缓存返回:{}",t);
return t;
}
从第6步可以看看出lock.tryLock尝试加锁,并限制只有一个用户查询数据库。从而解决了缓存击穿现象。
1.4.3、测试
@Test
public void testListCache() throws InterruptedException {
String key ="testListCache_101010101";
//初始化50个线程,让每个线程执行一个请求
ExecutorService executorServicePool = Executors.newFixedThreadPool(50);
//外部阻塞
CountDownLatch countDownLatch = new CountDownLatch(50);
//内部阻塞
CyclicBarrier cyclicBarrier = new CyclicBarrier(50);
for (int i = 0; i < 50; i++) {
executorServicePool.execute(()-> {
//阻塞线程等待
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
log.info("请求线程"+Thread.currentThread().getId()+"时间:{}",new Date());
redisCacheService.listCache(() -> {
log.info("执行数据查询");
List<User> list = new ArrayList<>();
list.add(User.builder().id(1111L).build());
return list;
}, key);
log.info("处理线程" + Thread.currentThread().getId() + "时间:{}", new Date());
//等待数-1,
countDownLatch.countDown();
});
}
countDownLatch.await();
}
测试结果表示,当缓存中没有信息时,只有第一个用户读取了数据库以后的用户访问直接从缓冲中读取。
1.5、雪崩
1.5.1、缓存雪崩
**缓存雪崩:**缓存雪崩一般是因为大批量的数据过期而造成的,而查询数据量巨大,引起数据压力过大甚至宕机。和缓存击穿不同的是,缓存击穿只是同一条数据过期,而缓存雪崩是不同数据都过期了,这些数据都必须去数据库中查询,而造成数据库压力增大,严重的导致缓存雪崩现象。
**限制的目标:**为不同的数据设计不同的到期时间
**解决方案:**为不同的数据设计不同的到期时间(eg:在缓存穿透的解决方案的代码里有一个随机生成30分钟-1小时之间的数据缓存到期时间,这个方法就是针对雪崩而设置的)
1.5.2、缓存雪崩解决方案
随机生成的时间代码如下,在为缓存数据指定存活的时间时,如果之前指定过则按照指定的来,如果没有指定的话就按照随机生成的。
/**
* @Description 产生1800到3600秒之间的整数
*/
private Integer RandomTime(){
int max=3600;
int min=1800;
Random random = new Random();
return random.nextInt(max)%(max-min+1) + min;
}
2、缓存总结
redis作为缓存最常见的问题,缓存穿透,缓存击穿和缓存雪崩。这三种现象对应的问题不同。
缓存穿透:主要针对于缓存和数据库中都没有数据,而用户还一致发送请求查询数据库,照成数据库压力过大,形成缓存穿透现象。针对此的解决方案时限流:限制同一个用户在单位时间内访问同一个方法的频次。
缓存击穿:主要针对于缓存中没有数据而数据库中有数据,而不同用户请求同一个方法,不同用户同时访问同一个方法而造成数据库压力过大而形成缓存击穿的现象。针对此方案就是加锁,限制同一时间内访问数据库的用户个数。拿到锁的用户访问数据库,其它用户只能等待。
缓存雪崩:主要正对于缓存中的数据同一时间大批量过期的现象,造成这样的原因时因为缓存数据的过期时间一致。解决方案是给不同的缓存数据设置不同的存活时间。