一篇文章读懂redis

缓存穿透高并发下查询一个值,缓存中没有,数据库中也没有,布隆过滤器
解决方案:

  • 如果数据库中值为空,把空写入缓存即可 。
  • 也可以把所有的可能存在的key放入到一个大的Bitmap中,查询时通过该Bitmap过滤
缓存雪崩缓存中大量数据同时到期,高并发下,所有请求都走向数据库
解决方案:
尽量不要把所有缓存都设置在同一时间过期, 通过加锁或者队列只允许一个线程查询数据库和写缓存, 其他线程等待.
通过加锁或者队列只允许一个线程查询数据库和写缓存,其他线程等待 。
热点缓存(缓存击穿)双重检测锁解决热点缓存问题,需要加volatile防止指令重排
高并发下,一个热点缓存到期,然后去数据库中去取,当还没有放入缓存中时,大量请求过来
解决方案:
  • 双重检测锁
Integer count = redis.get("key");if (count == null) {  synchronized {    count = redis.get("key");    if (count == null) {      count = repo.getCount();      redis.put("key", count);  }}} 
  • 也可以用redis的setnx互斥锁进行判断
if (redis.setnx(lockKey, requestId, NX, PX) == 1) {} 
缓存双写一致性解决方案:
延时双删策略, 先更新数据库,再删缓存
public void write(String key,Object data){  redis.delKey(key);  db.updateData(data);  // 可以将以下两步作为异步处理  Thread.sleep(1000);  redis.delKey(key);}Redis简介Redis是一种用C语言开发的,高性能的,键值对key-value形式的noSql数据库
支持5种string, hash, set, list, 有序集合类型(sorted set, 简称zset)等数据类型
劣势就是存储的数据缺少结构化
应用场景:
  • 内存数据库(登录信息,购物车信息,用户浏览记录)
  • 缓存信息
  • 解决分布式架构中的session分离问题
redis常用命令
  • redis-server
  • redis-client
  • 性能测试工具redis-benchmarkredis-benchmark -q(Quiet. Just show query/sec values) -n(default 100000 requests)-h <hostname> Server hostname (default 127.0.0.1) -p <port> Server port (default 6379) -s <socket> Server socket (overrides host and port) -a <password> Password for Redis Auth -c <clients> Number of parallel connections (default 50) -n <requests> Total number of requests (default 100000) -d <size> Data size of SET/GET value in bytes (default 2) -dbnum <db> SELECT the specified db number (default 0) -k <boolean> 1=keep alive 0=reconnect (default 1) -r <keyspacelen> Use random keys for SET/GET/INCR, random values for SADD Using this option the benchmark will expand the string rand_int inside an argument with a 12 digits number in the specified range from 0 to keyspacelen-1. The substitution changes every time a command is executed. Default tests use this to hit random keys in the specified range. -P <numreq> Pipeline <numreq> requests. Default 1 (no pipeline). -q Quiet. Just show query/sec values --csv Output in CSV format -l Loop. Run the tests forever -t <tests> Only run the comma separated list of tests. The test names are the same as the ones produced as output. -I Idle mode. Just open N idle connections and wait.
  • redis-check-aofaof文件检查的工具
  • redis-check-dumprdb文件进行检查的工具
  • redis-sentinel启动哨兵监控服务
redis数据类型及常用操作