(一)缓存和数据库间数据一致性问题
分布式环境下(单机就不用说了)非常容易出现缓存和数据库间的数据一致性问题,针对这一点的话,只能说,如果你的项目对缓存的要求是强一致性的,那么请不要使用缓存。我们只能采取合适的策略来降低缓存和数据库间数据不一致的概率,而无法保证两者间的强一致性。合适的策略包括 合适的缓存更新策略,更新数据库后要及时更新缓存、缓存失败时增加重试机制,例如MQ模式的消息队列。
(二)缓存击穿问题
缓存击穿表示恶意用户模拟请求很多缓存中不存在的数据,由于缓存中都没有,导致这些请求短时间内直接落在了数据库上,导致数据库异常。这个我们在实际项目就遇到了,有些抢购活动、秒杀活动的接口API被大量的恶意用户刷,导致短时间内数据库宕机了,好在数据库是多主多从的,hold住了。
解决方案的话:
1、使用互斥锁排队
业界比价普遍的一种做法,即根据key获取value值为空时,锁上,从数据库中load数据后再释放锁。若其它线程获取锁失败,则等待一段时间后重试。这里要注意,分布式环境中要使用分布式锁,单机的话用普通的锁(synchronized、Lock)就够了。
一、加锁操作
1<dependency> 2 <groupId>redis.clients</groupId> 3 <artifactId>jedis</artifactId> 4 <version>2.9.0</version> 5</dependency> 6 7private static final String LOCKED_SUCCESS = "OK"; 8private static final String NX = "NX"; 9private static final String EXPIRE_TIME = "PX"; 10 11/** 12* 获取锁 13* 14* @param jedis redis客户端 15* @param lockKey 锁的key 16* @param uniqueId 请求标识 17* @param expireTime 过期时间 18* @return 是否获取锁 19*/ 20public static boolean tryDistributedLock(Jedis jedis, String lockKey, String uniqueId, long expireTime) { 21 String result = jedis.set(lockKey, uniqueId, NX, EXPIRE_TIME, expireTime); 22 return LOCKED_SUCCESS.equals(result); 23}
在低版本的redis中是没有这个set方法的,至于为什么这个简单的set方法能够保证前面提到的分布式锁原则呢?看下这个set的源码参数
1/** 2* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 3* GB). 4* @param key 唯一标识key 5* @param value 存储的值value 6* @param nxxx 可选项:NX、XX 其中NX表示当key不存在时才set值,XX表示当key存在时才set值 7* @param expx 过期时间单位,可选项:EX|PX 其中EX为seconds,PX为milliseconds 8* @param time 过期时间,单位取上一个参数 9* @return Status code reply 10*/ 11public String set(final String key, final String value, final String nxxx, final String expx, 12 final long time) { 13 checkIsInMultiOrPipeline(); 14 client.set(key, value, nxxx, expx, time); 15 return client.getStatusCodeReply(); 16}
如上的tryDistributedLock就可以实现简单的redis分布式锁了(此set方法的原子性)
1、set方法中nxx参数为NX,表示当key不存在时才会set值,保证了互斥性;
2、set值的同时设置过期时间(过期后del此key),客户端宕机或网络延迟时不会一直持有锁,避免了死锁发生;
3、set方法中的value,比如UUID之类的,用来表示当前请求客户端的唯一性标识;
4、因为是redis单例,暂时没有考虑容错性;
常见的错误分布式加锁实现
1private static final Long RELEASE_SUCCESS = 1L; 2 3/** 4* 释放锁 5* 6* @param jedis redis客户端 7* @param lockKey 锁的key 8* @param uniqueId 请求标识 9* @return 是否释放 10*/ 11public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String uniqueId) { 12 String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; 13 Object result = jedis.eval(luaScript, Collections.singletonList(lockKey), Collections.singletonList(uniqueId)); 14 return RELEASE_SUCCESS.equals(result); 15}
二、解锁操作
1private static final Long RELEASE_SUCCESS = 1L; 2 3/** 4* 释放锁 5* 6* @param jedis redis客户端 7* @param lockKey 锁的key 8* @param uniqueId 请求标识 9* @return 是否释放 10*/ 11public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String uniqueId) { 12 String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; 13 Object result = jedis.eval(luaScript, Collections.singletonList(lockKey), Collections.singletonList(uniqueId)); 14 return RELEASE_SUCCESS.equals(result); 15}
不难看出使用Lua脚本告诉redis,如果这个key存在,且其存储的值和指定的value一致才可以删除这个key,从而释放锁,这样也保证了分布式锁的几个原则. 常见的错误释放锁会直接del这个key,没有考虑当前锁的拥有者,不符合分布式锁原则的有始有终原则;
如果不想用上面的Lua脚本,也可以用如下代码:
1public static void releaseLock(Jedis jedis,String lockKey,String uniqueId){ 2 if(uniqueId.equals(jedis.get(lockKey))){ 3 jedis.del(lockKey); 4 } 5} 6 7public String getWithLock( String key, Jedis jedis, String lockKey, String uniqueId, long expireTime ) 8{ 9 /* 通过key获取value */ 10 String value = redisService.get( key ); 11 if ( StringUtil.isEmpty( value ) ) 12 { 13 /* 14 * 分布式锁,详细可以参考https://blog.csdn.net/fanrenxiang/article/details/79803037 15 * 封装的tryDistributedLock包括setnx和expire两个功能,在低版本的redis中不支持 16 */ 17 try { 18 boolean locked = redisService.tryDistributedLock( jedis, lockKey, uniqueId, expireTime ); 19 if ( locked ) 20 { 21 value = userService.getById( key ); 22 redisService.set( key, value ); 23 redisService.del( lockKey ); 24 return(value); 25 } else { 26 /* 其它线程进来了没获取到锁便等待50ms后重试 */ 27 Thread.sleep( 50 ); 28 getWithLock( key, jedis, lockKey, uniqueId, expireTime ); 29 } 30 } catch ( Exception e ) { 31 log.error( "getWithLock exception=" + e ); 32 return(value); 33 } finally { 34 redisService.releaseDistributedLock( jedis, lockKey, uniqueId ); 35 } 36 } 37 return(value); 38}
这样做思路比较清晰,也从一定程度上减轻数据库压力,但是锁机制使得逻辑的复杂度增加,吞吐量也降低了,有点治标不治本。
2、布隆过滤器(推荐)
bloomfilter就类似于一个hash set,用于快速判某个元素是否存在于集合中,其典型的应用场景就是快速判断一个key是否存在于某容器,不存在就直接返回。布隆过滤器的关键就在于hash算法和容器大小,下面先来简单的实现下看看效果,我这里用guava实现的布隆过滤器:
1<dependencies > 2 < dependency > 3 < groupId > com.google.guava</ groupId> 4 < artifactId > guava</ artifactId> 5 < version > 23.0 < / version > 6 < / dependency > 7 < / dependencies > 8 public class BloomFilterTest { 9 private static final int capacity = 1000000; 10 private static final int key = 999998; 11 private static BloomFilter<Integer> bloomFilter = BloomFilter.create( Funnels.integerFunnel(), capacity ); 12 static { 13 for ( int i = 0; i < capacity; i++ ) 14 { 15 bloomFilter.put( i ); 16 } 17 } 18 public static void main( String[] args ) 19 { 20 /*返回计算机最精确的时间,单位微妙*/ 21 long start = System.nanoTime(); 22 if ( bloomFilter.mightContain( key ) ) 23 { 24 System.out.println( "成功过滤到" + key ); 25 } 26 long end = System.nanoTime(); 27 System.out.println( "布隆过滤器消耗时间:" + (end - start) ); 28 int sum = 0; 29 for ( int i = capacity + 20000; i < capacity + 30000; i++ ) 30 { 31 if ( bloomFilter.mightContain( i ) ) 32 { 33 sum = sum + 1; 34 } 35 } 36 System.out.println( "错判率为:" + sum ); 37 } 38 } 39 成 功过滤到999998 40 布 隆过滤器消 耗 时间 : 215518 41 错 判率 为 : 318
可以看到,100w个数据中只消耗了约0.2毫秒就匹配到了key,速度足够快。然后模拟了1w个不存在于布隆过滤器中的key,匹配错误率为318/10000,也就是说,出错率大概为3%,跟踪下BloomFilter的源码发现默认的容错率就是0.03:
1public static < T > BloomFilter<T> create( Funnel<T> funnel, int expectedInsertions /* n */ ) 2{ 3 return(create( funnel, expectedInsertions, 0.03 ) ); /* FYI, for 3%, we always get 5 hash functions */ 4}
要注意的是,布隆过滤器不支持删除操作。用在这边解决缓存穿透问题就是:
1public String getByKey( String key ) 2{ 3 /* 通过key获取value */ 4 String value = redisService.get( key ); 5 if ( StringUtil.isEmpty( value ) ) 6 { 7 if ( bloomFilter.mightContain( key ) ) 8 { 9 value = userService.getById( key ); 10 redisService.set( key, value ); 11 return(value); 12 } else { 13 return(null); 14 } 15 } 16 return(value); 17}
(三)缓存雪崩问题
缓存在同一时间内大量键过期(失效),接着来的一大波请求瞬间都落在了数据库中导致连接异常。
解决方案:
1、也是像解决缓存穿透一样加锁排队,实现同上;
2、建立备份缓存,缓存A和缓存B,A设置超时时间,B不设值超时时间,先从A读缓存,A没有读B,并且更新A缓存和B缓存;
1public String getByKey( String keyA, String keyB ) 2{ 3 String value = redisService.get( keyA ); 4 if ( StringUtil.isEmpty( value ) ) 5 { 6 value = redisService.get( keyB ); 7 String newValue = getFromDbById(); 8 redisService.set( keyA, newValue, 31, TimeUnit.DAYS ); 9 redisService.set( keyB, newValue ); 10 } 11 return(value); 12}