Redis缓存Redis

Redis 四连发:缓存雪崩、穿透、预热、降级

2019-03-22  本文已影响635人  他是人间惆怅客

一.Redis缓存雪崩

Redis缓存雪崩和穿透乍一看好像差不多,概念容易混淆.
缓存雪崩是指在我们设置缓存失效时间上时采用了相同的过期时间,导致缓存在某一时刻同时失效,请求全部打到后端数据库,数据库一时请求过大,数据库cpu和IO一时负载过大,造成雪崩。如果不能理解的话,闭上眼睛想象一下,雪山崩塌的场景,还不能理解的话,那就算了吧.

用户请求.jpg

这块其实业界有很多解决方案,但是每一种方案说是完美的,需要结合实际并发量.第一种就是加锁排队,串行的去执行,但是这本质上是一种缓解,允许等待,从用户角度来说不是很好.第二种比较多的就是mutex互斥锁,比如Redis分布式锁SetNX,如果缓存里面没有并不是去加载数据库.第三种限流:比如用滑动窗口控制,在大流量来的时候缩紧;或者通过令牌桶、漏桶算法等.第四种就是做二级缓存,或者双缓存策略。比如B为原始缓存,B2为拷贝缓存,B失效时,可以访问B2,B1缓存失效时间设置为短期,B2设置为长期。这块有点master-slave,主从的意思.
这些技术手段,想达到的终极目标无外乎就是让失效时间达到均匀的状态.

二.Redis穿透
Redis穿透是大量的请求在缓存中没有命中,导致每次都要到数据库里面去查询,这样导致缓存被穿透.
解决方案:
1.Bloom filter
布隆过滤器背景:(Bloom Filter)是由伯顿·布隆(Burton Bloom)于1970年提出来的,它实际上是一个很长的二进制向量和一系列随机映射函数。
我们知道Redis之所以快除了单线程避免了CPU上下文切换,采用了epoll机制,还有一个重要的问题是他的存储结构,时间复杂度是o(1),但是redis的存储空间是很珍贵的,过多的key对于redis来说是一件麻烦的事情,比如你有几亿个key,这种一股脑的丢到Redis,很不合理.Bloom Filter或许就是一种改善的解决方案,极大的减小了存储空间.布隆过滤器是一个位向量或者说是位数组.

但是对于布隆过滤器的一定要谨慎,Bloom过滤器比较鸡肋的地方是它存在一定的概率的误判,我们在学术上称他为假阳性,而且随着元素的增加,这种误判的机率会随着增加,但是误判的概率几乎可以忽略,影响不到,一般key不多的情况,用散列表就可以了,唯一的好处就是节省空间.目前它只支持add和isExist操作,不支持delete操作,这个理解它的原理的很容易明白,因为你删除更新那一位1,正好可能也是别的key的entry.下面看一下代码吧:

布隆过滤器在Guava中的实现:

创建:
static <T> BloomFilter<T> create(
Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) {
checkNotNull(funnel);
checkArgument(
expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions);
checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp);
checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp);
checkNotNull(strategy);

if (expectedInsertions == 0) {
  expectedInsertions = 1;
}
/*
 * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size
 * is proportional to -log(p), but there is not much of a point after all, e.g.
 * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares!
 */
long numBits = optimalNumOfBits(expectedInsertions, fpp);
int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
try {
  return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, strategy);
} catch (IllegalArgumentException e) {
  throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e);
}

}

create里面有4个参数,funnel:输入的数据,expectedInsertions:预估计插入的元素总量,fpp:你自己想达到的误判率,strategy:实现的实例
BloomFilterStrategies类:
MURMUR128_MITZ_64() {
@Override
public <T> boolean put(
T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) {
long bitSize = bits.bitSize();
byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal();
long hash1 = lowerEight(bytes);
long hash2 = upperEight(bytes);

  boolean bitsChanged = false;
  long combinedHash = hash1;
  for (int i = 0; i < numHashFunctions; i++) {
    // Make the combined hash positive and indexable
    bitsChanged |= bits.set((combinedHash & Long.MAX_VALUE) % bitSize);
    combinedHash += hash2;
  }
  return bitsChanged;
}

@Override
public <T> boolean mightContain(
    T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) {
  long bitSize = bits.bitSize();
  byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal();
  long hash1 = lowerEight(bytes);
  long hash2 = upperEight(bytes);

  long combinedHash = hash1;
  for (int i = 0; i < numHashFunctions; i++) {
    // Make the combined hash positive and indexable
    if (!bits.get((combinedHash & Long.MAX_VALUE) % bitSize)) {
      return false;
    }
    combinedHash += hash2;
  }
  return true;
}

底层bit数组实现:
static final class BitArray {
final long[] data;
long bitCount;

BitArray(long bits) {
  this(new long[Ints.checkedCast(LongMath.divide(bits, 64, RoundingMode.CEILING))]);
}

// Used by serialization
BitArray(long[] data) {
  checkArgument(data.length > 0, "data length is zero!");
  this.data = data;
  long bitCount = 0;
  for (long value : data) {
    bitCount += Long.bitCount(value);
  }
  this.bitCount = bitCount;
}

/** Returns true if the bit changed value. */
boolean set(long index) {
  if (!get(index)) {
    data[(int) (index >>> 6)] |= (1L << index);
    bitCount++;
    return true;
  }
  return false;
}

boolean get(long index) {
  return (data[(int) (index >>> 6)] & (1L << index)) != 0;
}

/** Number of bits */
long bitSize() {
  return (long) data.length * Long.SIZE;
}

...
}

2.缓存这些空对象,但是注意失效时间设置的小一点,防止Redis的key过多.

三.Redis预热
缓存预热就是系统发布之前,先把缓存数据加载到缓存系统里面,这样避免了活动正式开始之前,首次没有命中,要查数据库的问题,另外一方面预热也是提前对流量的一种预估方式,很多大型活动或者秒杀,都会提前来一波预热.

四.Redis降级
当并发量大的时候,响应很慢或者超时,影响到核心链路的业务处理(比如支付、订单等),或者导致到上游的系统的扇出,这种情形我需要对服务进行降级,换句话说就是保帅丢兵的思想.

上一篇下一篇

猜你喜欢

热点阅读