原文链接:https://blog.youkuaiyun.com/fanrenxiang/article/details/80542580
把redis作为缓存使用已经是司空见惯,但是使用redis后也可能会碰到一系列的问题,尤其是数据量很大的时候,经典的几个问题如下:
(一)缓存和数据库间数据一致性问题
分布式环境下(单机就不用说了)非常容易出现缓存和数据库间的数据一致性问题,针对这一点的话,只能说,如果你的项目对缓存的要求是强一致性的,那么请不要使用缓存。我们只能采取合适的策略来降低缓存和数据库间数据不一致的概率,而无法保证两者间的强一致性。合适的策略包括 合适的缓存更新策略,更新数据库后要及时更新缓存、缓存失败时增加重试机制,例如MQ模式的消息队列。
(二)缓存击穿问题
缓存击穿表示恶意用户模拟请求很多缓存中不存在的数据,由于缓存中都没有,导致这些请求短时间内直接落在了数据库上,导致数据库异常。这个我们在实际项目就遇到了,有些抢购活动、秒杀活动的接口API被大量的恶意用户刷,导致短时间内数据库c超时了,好在数据库是读写分离,同时也有进行接口限流,hold住了。
解决方案的话:
方案1、使用互斥锁排队
业界比价普遍的一种做法,即根据key获取value值为空时,锁上,从数据库中load数据后再释放锁。若其它线程获取锁失败,则等待一段时间后重试。这里要注意,分布式环境中要使用分布式锁,单机的话用普通的锁(synchronized、Lock)就够了。
-
public String getWithLock(String key, Jedis jedis, String lockKey, String uniqueId, long expireTime) {
-
// 通过key获取value
-
String value = redisService.get(key);
-
if (StringUtil.isEmpty(value)) {
-
// 分布式锁,详细可以参考https://blog.youkuaiyun.com/fanrenxiang/article/details/79803037
-
//封装的tryDistributedLock包括setnx和expire两个功能,在低版本的redis中不支持
-
try {
-
boolean locked = redisService.tryDistributedLock(jedis, lockKey, uniqueId, expireTime);
-
if (locked) {
-
value = userService.getById(key);
-
redisService.set(key, value);
-
redisService.del(lockKey);
-
return value;
-
}
else {
-
// 其它线程进来了没获取到锁便等待50ms后重试
-
Thread.sleep(
50);
-
getWithLock(key, jedis, lockKey, uniqueId, expireTime);
-
}
-
}
catch (Exception e) {
-
log.error(
"getWithLock exception=" + e);
-
return value;
-
}
finally {
-
redisService.releaseDistributedLock(jedis, lockKey, uniqueId);
-
}
-
}
-
return value;
-
}
这样做思路比较清晰,也从一定程度上减轻数据库压力,但是锁机制使得逻辑的复杂度增加,吞吐量也降低了,有点治标不治本。
方案2、接口限流与熔断、降级
重要的接口一定要做好限流策略,防止用户恶意刷接口,同时要降级准备,当接口中的某些服务不可用时候,进行熔断,失败快速返回机制。
方案3、布隆过滤器
bloomfilter就类似于一个hash set,用于快速判某个元素是否存在于集合中,其典型的应用场景就是快速判断一个key是否存在于某容器,不存在就直接返回。布隆过滤器的关键就在于hash算法和容器大小,下面先来简单的实现下看看效果,我这里用guava实现的布隆过滤器:
-
<dependencies>
-
<dependency>
-
<groupId>com.google.guava</groupId>
-
<artifactId>guava</artifactId>
-
<version>
23.0</version>
-
</dependency>
-
</dependencies>
-
public
class BloomFilterTest {
-
-
private
static
final
int capacity =
1000000;
-
private
static
final
int key =
999998;
-
-
private
static BloomFilter<Integer> bloomFilter = BloomFilter.create(Funnels.integerFunnel(), capacity);
-
-
static {
-
for (
int i =
0; i < capacity; i++) {
-
bloomFilter.put(i);
-
}
-
}
-
-
public static void main(String[] args) {
-
/*返回计算机最精确的时间,单位微妙*/
-
long start = System.nanoTime();
-
-
if (bloomFilter.mightContain(key)) {
-
System.out.println(
"成功过滤到" + key);
-
}
-
long end = System.nanoTime();
-
System.out.println(
"布隆过滤器消耗时间:" + (end - start));
-
int sum =
0;
-
for (
int i = capacity +
20000; i < capacity +
30000; i++) {
-
if (bloomFilter.mightContain(i)) {
-
sum = sum +
1;
-
}
-
}
-
System.out.println(
"错判率为:" + sum);
-
}
-
}
-
成功过滤到
999998
-
布隆过滤器消耗时间:
215518
-
错判率为:
318
可以看到,100w个数据中只消耗了约0.2毫秒就匹配到了key,速度足够快。然后模拟了1w个不存在于布隆过滤器中的key,匹配错误率为318/10000,也就是说,出错率大概为3%,跟踪下BloomFilter的源码发现默认的容错率就是0.03:
-
public
static <T>
BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) {
-
return create(funnel, expectedInsertions,
0.03);
// FYI, for 3%, we always get 5 hash functions
-
}
我们可调用BloomFilter的这个方法显式的指定误判率:
private static BloomFilter<Integer> bloomFilter = BloomFilter.create(Funnels.integerFunnel(), capacity,0.01);
我们断点跟踪下,误判率为0.02和默认的0.03时候的区别:
对比两个出错率可以发现,误判率为0.02时数组大小为8142363,0.03时为7298440,误判率降低了0.01,BloomFilter维护的数组大小也减少了843923,可见BloomFilter默认的误判率0.03是设计者权衡系统性能后得出的值。要注意的是,布隆过滤器不支持删除操作。用在这边解决缓存穿透问题就是:
-
public String getByKey(String key) {
-
// 通过key获取value
-
String value = redisService.get(key);
-
if (StringUtil.isEmpty(value)) {
-
if (bloomFilter.mightContain(key)) {
-
value = userService.getById(key);
-
redisService.set(key, value);
-
return value;
-
}
else {
-
return
null;
-
}
-
}
-
return value;
-
}
(三)缓存雪崩问题
缓存在同一时间内大量键过期(失效),接着来的一大波请求瞬间都落在了数据库中导致连接异常。
解决方案:
方案1、也是像解决缓存穿透一样加锁排队,实现同上;
方案2、建立备份缓存,缓存A和缓存B,A设置超时时间,B不设值超时时间,先从A读缓存,A没有读B,并且更新A缓存和B缓存;
方案3、设置缓存超时时间的时候加上一个随机的时间长度,比如这个缓存key的超时时间是固定的5分钟加上随机的2分钟,酱紫可从一定程度上避免雪崩问题;
-
public String getByKey(String keyA,String keyB) {
-
String value = redisService.get(keyA);
-
if (StringUtil.isEmpty(value)) {
-
value = redisService.get(keyB);
-
String newValue = getFromDbById();
-
redisService.set(keyA,newValue,
31, TimeUnit.DAYS);
-
redisService.set(keyB,newValue);
-
}
-
return value;
-
}
(四)缓存并发问题
这里的并发指的是多个redis的client同时set key引起的并发问题。其实redis自身就是单线程操作,多个client并发操作,按照先到先执行的原则,先到的先执行,其余的阻塞。当然,另外的解决方案是把redis.set操作放在队列中使其串行化,必须的一个一个执行,具体的代码就不上了,当然加锁也是可以的,至于为什么不用redis中的事务,留给各位看官自己思考探究。
引申阅读: 使用quartz实现高级定制化定时任务(包含管理界面)
推荐阅读:elastic search搜索引擎实战demo:https://github.com/simonsfan/springboot-quartz-demo,分支:feature_es