redis系列之数据库与缓存数据一致性解决方案

时间:2022-03-16 19:56:25

redis系列之数据库与缓存数据一致性解决方案

数据库与缓存读写模式策略

写完数据库后是否需要马上更新缓存还是直接删除缓存?
(1)、如果写数据库的值与更新到缓存值是一样的,不需要经过任何的计算,可以马上更新缓存,但是如果对于那种写数据频繁而读数据少的场景并不合适这种解决方案,因为也许还没有查询就被删除或修改了,这样会浪费时间和资源
(2)、如果写数据库的值与更新缓存的值不一致,写入缓存中的数据需要经过几个表的关联计算后得到的结果插入缓存中,那就没有必要马上更新缓存,只有删除缓存即可,等到查询的时候在去把计算后得到的结果插入到缓存中即可。
所以一般的策略是当更新数据时,先删除缓存数据,然后更新数据库,而不是更新缓存,等要查询的时候才把最新的数据更新到缓存

数据库与缓存双写情况下导致数据不一致问题

场景一

当更新数据时,如更新某商品的库存,当前商品的库存是100,现在要更新为99,先更新数据库更改成99,然后删除缓存,发现删除缓存失败了,这意味着数据库存的是99,而缓存是100,这导致数据库和缓存不一致。

场景一解决方案

 
 
这种情况应该是先删除缓存,然后在更新数据库,如果删除缓存失败,那就不要更新数据库,如果说删除缓存成功,而更新数据库失败,那查询的时候只是从数据库里查了旧的数据而已,这样就能保持数据库与缓存的一致性。

场景二

在高并发的情况下,如果当删除完缓存的时候,这时去更新数据库,但还没有更新完,另外一个请求来查询数据,发现缓存里没有,就去数据库里查,还是以上面商品库存为例,如果数据库中产品的库存是100,那么查询到的库存是100,然后插入缓存,插入完缓存后,原来那个更新数据库的线程把数据库更新为了99,导致数据库与缓存不一致的情况

场景二解决方案

 
遇到这种情况,可以用队列的去解决这个问,创建几个队列,如20个,根据商品的ID去做hash值,然后对队列个数取摸,当有数据更新请求时,先把它丢到队列里去,当更新完后在从队列里去除,如果在更新的过程中,遇到以上场景,先去缓存里看下有没有数据,如果没有,可以先去队列里看是否有相同商品ID在做更新,如果有也把查询的请求发送到队列里去,然后同步等待缓存更新完成。
这里有一个优化点,如果发现队列里有一个查询请求了,那么就不要放新的查询操作进去了,用一个while(true)循环去查询缓存,循环个200MS左右,如果缓存里还没有则直接取数据库的旧数据,一般情况下是可以取到的。
 
在高并发下解决场景二要注意的问题
(1)读请求时长阻塞
 由于读请求进行了非常轻度的异步化,所以一定要注意读超时的问题,每个读请求必须在超时间内返回,该解决方案最大的风险在于可能数据更新很频繁,导致队列中挤压了大量的更新操作在里面,然后读请求会发生大量的超时,最后导致大量的请求直接走数据库,像遇到这种情况,一般要做好足够的压力测试,如果压力过大,需要根据实际情况添加机器。
(2)请求并发量过高
 这里还是要做好压力测试,多模拟真实场景,并发量在最高的时候QPS多少,扛不住就要多加机器,还有就是做好读写比例是多少
(3)多服务实例部署的请求路由
可能这个服务部署了多个实例,那么必须保证说,执行数据更新操作,以及执行缓存更新操作的请求,都通过nginx服务器路由到相同的服务实例上
(4)热点商品的路由问题,导致请求的倾斜
某些商品的读请求特别高,全部打到了相同的机器的相同丢列里了,可能造成某台服务器压力过大,因为只有在商品数据更新的时候才会清空缓存,然后才会导致读写并发,所以更新频率不是太高的话,这个问题的影响并不是很大,但是确实有可能某些服务器的负载会高一些。
 

数据库与缓存数据一致性解决方案流程图

redis系列之数据库与缓存数据一致性解决方案

数据库与缓存数据一致性解决方案对应代码

 

商品库存实体

  1. package com.shux.inventory.entity;
  2. /**
  3. **********************************************
  4. *  描述:
  5. * Simba.Hua
  6. * 2017年8月30日
  7. **********************************************
  8. **/
  9. public class InventoryProduct {
  10. private Integer productId;
  11. private Long InventoryCnt;
  12. public Integer getProductId() {
  13. return productId;
  14. }
  15. public void setProductId(Integer productId) {
  16. this.productId = productId;
  17. }
  18. public Long getInventoryCnt() {
  19. return InventoryCnt;
  20. }
  21. public void setInventoryCnt(Long inventoryCnt) {
  22. InventoryCnt = inventoryCnt;
  23. }
  24. }

请求接口

  1. /**
  2. **********************************************
  3. *  描述:
  4. * Simba.Hua
  5. * 2017年8月27日
  6. **********************************************
  7. **/
  8. public interface Request {
  9. public void process();
  10. public Integer getProductId();
  11. public boolean isForceFefresh();
  12. }

数据更新请求

  1. package com.shux.inventory.request;
  2. import org.springframework.transaction.annotation.Transactional;
  3. import com.shux.inventory.biz.InventoryProductBiz;
  4. import com.shux.inventory.entity.InventoryProduct;
  5. /**
  6. **********************************************
  7. *  描述:更新库存信息
  8. *  1、先删除缓存中的数据
  9. *  2、更新数据库中的数据
  10. * Simba.Hua
  11. * 2017年8月30日
  12. **********************************************
  13. **/
  14. public class InventoryUpdateDBRequest implements Request{
  15. private InventoryProductBiz inventoryProductBiz;
  16. private InventoryProduct inventoryProduct;
  17. public InventoryUpdateDBRequest(InventoryProduct inventoryProduct,InventoryProductBiz inventoryProductBiz){
  18. this.inventoryProduct = inventoryProduct;
  19. this.inventoryProductBiz = inventoryProductBiz;
  20. }
  21. @Override
  22. @Transactional
  23. public void process() {
  24. inventoryProductBiz.removeInventoryProductCache(inventoryProduct.getProductId());
  25. inventoryProductBiz.updateInventoryProduct(inventoryProduct);
  26. }
  27. @Override
  28. public Integer getProductId() {
  29. // TODO Auto-generated method stub
  30. return inventoryProduct.getProductId();
  31. }
  32. @Override
  33. public boolean isForceFefresh() {
  34. // TODO Auto-generated method stub
  35. return false;
  36. }
  37. }

查询请求

  1. package com.shux.inventory.request;
  2. import com.shux.inventory.biz.InventoryProductBiz;
  3. import com.shux.inventory.entity.InventoryProduct;
  4. /**
  5. **********************************************
  6. *  描述:查询缓存数据
  7. *  1、从数据库中查询
  8. *  2、从数据库中查询后插入到缓存中
  9. * Simba.Hua
  10. * 2017年8月30日
  11. **********************************************
  12. **/
  13. public class InventoryQueryCacheRequest implements Request {
  14. private InventoryProductBiz inventoryProductBiz;
  15. private Integer productId;
  16. private boolean isForceFefresh;
  17. public InventoryQueryCacheRequest(Integer productId,InventoryProductBiz inventoryProductBiz,boolean isForceFefresh) {
  18. this.productId = productId;
  19. this.inventoryProductBiz = inventoryProductBiz;
  20. this.isForceFefresh = isForceFefresh;
  21. }
  22. @Override
  23. public void process() {
  24. InventoryProduct  inventoryProduct = inventoryProductBiz.loadInventoryProductByProductId(productId);
  25. inventoryProductBiz.setInventoryProductCache(inventoryProduct);
  26. }
  27. @Override
  28. public Integer getProductId() {
  29. // TODO Auto-generated method stub
  30. return productId;
  31. }
  32. public boolean isForceFefresh() {
  33. return isForceFefresh;
  34. }
  35. public void setForceFefresh(boolean isForceFefresh) {
  36. this.isForceFefresh = isForceFefresh;
  37. }
  38. }

spring启动时初始化队列线程池

  1. package com.shux.inventory.thread;
  2. import java.util.concurrent.ArrayBlockingQueue;
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. import com.shux.inventory.request.Request;
  6. import com.shux.inventory.request.RequestQueue;
  7. import com.shux.utils.other.SysConfigUtil;
  8. /**
  9. **********************************************
  10. *  描述:请求处理线程池,初始化队列数及每个队列最多能处理的数量
  11. * Simba.Hua
  12. * 2017年8月27日
  13. **********************************************
  14. **/
  15. public class RequestProcessorThreadPool {
  16. private static final int blockingQueueNum = SysConfigUtil.get("request.blockingqueue.number")==null?10:Integer.valueOf(SysConfigUtil.get("request.blockingqueue.number").toString());
  17. private static final int queueDataNum = SysConfigUtil.get("request.everyqueue.data.length")==null?100:Integer.valueOf(SysConfigUtil.get("request.everyqueue.data.length").toString());
  18. private ExecutorService threadPool = Executors.newFixedThreadPool(blockingQueueNum);
  19. private RequestProcessorThreadPool(){
  20. for(int i=0;i<blockingQueueNum;i++){//初始化队列
  21. ArrayBlockingQueue<Request> queue = new ArrayBlockingQueue<Request>(queueDataNum);//每个队列中放100条数据
  22. RequestQueue.getInstance().addQueue(queue);
  23. threadPool.submit(new RequestProcessorThread(queue));//把每个queue交个线程去处理,线程会处理每个queue中的数据
  24. }
  25. }
  26. public static class Singleton{
  27. private static RequestProcessorThreadPool instance;
  28. static{
  29. instance = new RequestProcessorThreadPool();
  30. }
  31. public static RequestProcessorThreadPool getInstance(){
  32. return instance;
  33. }
  34. }
  35. public static RequestProcessorThreadPool getInstance(){
  36. return Singleton.getInstance();
  37. }
  38. /**
  39. * 初始化线程池
  40. */
  41. public static void init(){
  42. getInstance();
  43. }
  44. }

请求处理线程

  1. package com.shux.inventory.thread;
  2. import java.util.Map;
  3. import java.util.concurrent.ArrayBlockingQueue;
  4. import java.util.concurrent.Callable;
  5. import com.shux.inventory.request.InventoryUpdateDBRequest;
  6. import com.shux.inventory.request.Request;
  7. import com.shux.inventory.request.RequestQueue;
  8. /**
  9. **********************************************
  10. *  描述:请求处理线程
  11. * Simba.Hua
  12. * 2017年8月27日
  13. **********************************************
  14. **/
  15. public class RequestProcessorThread implements Callable<Boolean>{
  16. private ArrayBlockingQueue<Request> queue;
  17. public RequestProcessorThread(ArrayBlockingQueue<Request> queue){
  18. this.queue = queue;
  19. }
  20. @Override
  21. public Boolean call() throws Exception {
  22. Request request = queue.take();
  23. Map<Integer,Boolean> flagMap = RequestQueue.getInstance().getFlagMap();
  24. //不需要强制刷新的时候,查询请求去重处理
  25. if (!request.isForceFefresh()){
  26. if (request instanceof InventoryUpdateDBRequest) {//如果是更新请求,那就置为false
  27. flagMap.put(request.getProductId(), true);
  28. } else {
  29. Boolean flag = flagMap.get(request.getProductId());
  30. /**
  31. * 标志位为空,有三种情况
  32. * 1、没有过更新请求
  33. * 2、没有查询请求
  34. * 3、数据库中根本没有数据
  35. * 在最初情况,一旦库存了插入了数据,那就好会在缓存中也会放一份数据,
  36. * 但这种情况下有可能由于redis中内存满了,redis通过LRU算法把这个商品给清除了,导致缓存中没有数据
  37. * 所以当标志位为空的时候,需要从数据库重查询一次,并且把标志位置为false,以便后面的请求能够从缓存中取
  38. */
  39. if ( flag == null) {
  40. flagMap.put(request.getProductId(), false);
  41. }
  42. /**
  43. * 如果不为空,并且flag为true,说明之前有一次更新请求,说明缓存中没有数据了(更新缓存会先删除缓存),
  44. * 这个时候就要去刷新缓存,即从数据库中查询一次,并把标志位设置为false
  45. */
  46. if ( flag != null && flag) {
  47. flagMap.put(request.getProductId(), false);
  48. }
  49. /**
  50. * 这种情况说明之前有一个查询请求,并且把数据刷新到了缓存中,所以这时候就不用去刷新缓存了,直接返回就可以了
  51. */
  52. if (flag != null && !flag) {
  53. flagMap.put(request.getProductId(), false);
  54. return true;
  55. }
  56. }
  57. }
  58. request.process();
  59. return true;
  60. }
  61. }

请求队列

  1. package com.shux.inventory.request;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Map;
  5. import java.util.concurrent.ArrayBlockingQueue;
  6. import java.util.concurrent.ConcurrentHashMap;
  7. /**
  8. **********************************************
  9. *  描述:请求队列
  10. * Simba.Hua
  11. * 2017年8月27日
  12. **********************************************
  13. **/
  14. public class RequestQueue {
  15. private List<ArrayBlockingQueue<Request>> queues = new ArrayList<>();
  16. private Map<Integer,Boolean> flagMap = new ConcurrentHashMap<>();
  17. private RequestQueue(){
  18. }
  19. private static class Singleton{
  20. private static RequestQueue queue;
  21. static{
  22. queue = new RequestQueue();
  23. }
  24. public static RequestQueue getInstance() {
  25. return queue;
  26. }
  27. }
  28. public static RequestQueue getInstance(){
  29. return Singleton.getInstance();
  30. }
  31. public void addQueue(ArrayBlockingQueue<Request> queue) {
  32. queues.add(queue);
  33. }
  34. public int getQueueSize(){
  35. return queues.size();
  36. }
  37. public ArrayBlockingQueue<Request> getQueueByIndex(int index) {
  38. return queues.get(index);
  39. }
  40. public Map<Integer,Boolean> getFlagMap() {
  41. return this.flagMap;
  42. }
  43. }

spring 启动初始化线程池类

 
  1. package com.shux.inventory.listener;
  2. import org.springframework.context.ApplicationListener;
  3. import org.springframework.context.event.ContextRefreshedEvent;
  4. import com.shux.inventory.thread.RequestProcessorThreadPool;
  5. /**
  6. **********************************************
  7. *  描述:spring 启动初始化线程池类
  8. * Simba.Hua
  9. * 2017年8月27日
  10. **********************************************
  11. **/
  12. public class InitListener implements  ApplicationListener<ContextRefreshedEvent>{
  13. @Override
  14. public void onApplicationEvent(ContextRefreshedEvent event) {
  15. // TODO Auto-generated method stub
  16. if(event.getApplicationContext().getParent() != null){
  17. return;
  18. }
  19. RequestProcessorThreadPool.init();
  20. }
  21. }

异步处理请求接口

  1. package com.shux.inventory.biz;
  2. import com.shux.inventory.request.Request;
  3. /**
  4. **********************************************
  5. *  描述:请求异步处理接口,用于路由队列并把请求加入到队列中
  6. * Simba.Hua
  7. * 2017年8月30日
  8. **********************************************
  9. **/
  10. public interface IRequestAsyncProcessBiz {
  11. void process(Request request);
  12. }

异步处理请求接口实现

  1. package com.shux.inventory.biz.impl;
  2. import java.util.concurrent.ArrayBlockingQueue;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Service;
  6. import com.shux.inventory.biz.IRequestAsyncProcessBiz;
  7. import com.shux.inventory.request.Request;
  8. import com.shux.inventory.request.RequestQueue;
  9. /**
  10. **********************************************
  11. *  描述:异步处理请求,用于路由队列并把请求加入到队列中
  12. * Simba.Hua
  13. * 2017年8月30日
  14. **********************************************
  15. **/
  16. @Service("requestAsyncProcessService")
  17. public class RequestAsyncProcessBizImpl implements IRequestAsyncProcessBiz {
  18. private Logger logger = LoggerFactory.getLogger(getClass());
  19. @Override
  20. public void process(Request request) {
  21. // 做请求的路由,根据productId路由到对应的队列
  22. ArrayBlockingQueue<Request> queue = getQueueByProductId(request.getProductId());
  23. try {
  24. queue.put(request);
  25. } catch (InterruptedException e) {
  26. logger.error("产品ID{}加入队列失败",request.getProductId(),e);
  27. }
  28. }
  29. private ArrayBlockingQueue<Request> getQueueByProductId(Integer productId) {
  30. RequestQueue  requestQueue = RequestQueue.getInstance();
  31. String key = String.valueOf(productId);
  32. int hashcode;
  33. int hash = (key == null) ? 0 : (hashcode = key.hashCode())^(hashcode >>> 16);
  34. //对hashcode取摸
  35. int index = (requestQueue.getQueueSize()-1) & hash;
  36. return requestQueue.getQueueByIndex(index);
  37. }
  38. }

数据更新请求controller

  1. package com.shux.inventory.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. import com.shux.inventory.biz.IRequestAsyncProcessBiz;
  7. import com.shux.inventory.biz.InventoryProductBiz;
  8. import com.shux.inventory.entity.InventoryProduct;
  9. import com.shux.inventory.request.InventoryUpdateDBRequest;
  10. import com.shux.inventory.request.Request;
  11. import com.shux.utils.other.Response;
  12. /**
  13. **********************************************
  14. *  描述:提交更新请求
  15. * Simba.Hua
  16. * 2017年9月1日
  17. **********************************************
  18. **/
  19. @Controller("/inventory")
  20. public class InventoryUpdateDBController {
  21. private @Autowired InventoryProductBiz inventoryProductBiz;
  22. private @Autowired IRequestAsyncProcessBiz requestAsyncProcessBiz;
  23. @RequestMapping("/updateDBInventoryProduct")
  24. @ResponseBody
  25. public Response updateDBInventoryProduct(InventoryProduct  inventoryProduct){
  26. Request request = new InventoryUpdateDBRequest(inventoryProduct,inventoryProductBiz);
  27. requestAsyncProcessBiz.process(request);
  28. return new Response(Response.SUCCESS,"更新成功");
  29. }
  30. }

数据查询请求controller

  1. package com.shux.inventory.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import com.shux.inventory.biz.IRequestAsyncProcessBiz;
  6. import com.shux.inventory.biz.InventoryProductBiz;
  7. import com.shux.inventory.entity.InventoryProduct;
  8. import com.shux.inventory.request.InventoryQueryCacheRequest;
  9. import com.shux.inventory.request.Request;
  10. /**
  11. **********************************************
  12. *  描述:提交查询请求
  13. *  1、先从缓存中取数据
  14. *  2、如果能从缓存中取到数据,则返回
  15. *  3、如果不能从缓存取到数据,则等待20毫秒,然后再次去数据,直到200毫秒,如果超过200毫秒还不能取到数据,则从数据库中取,并强制刷新缓存数据
  16. * Simba.Hua
  17. * 2017年9月1日
  18. **********************************************
  19. **/
  20. @Controller("/inventory")
  21. public class InventoryQueryCacheController {
  22. private @Autowired InventoryProductBiz inventoryProductBiz;
  23. private @Autowired IRequestAsyncProcessBiz requestAsyncProcessBiz;
  24. @RequestMapping("/queryInventoryProduct")
  25. public InventoryProduct queryInventoryProduct(Integer productId) {
  26. Request request = new InventoryQueryCacheRequest(productId,inventoryProductBiz,false);
  27. requestAsyncProcessBiz.process(request);//加入到队列中
  28. long startTime = System.currentTimeMillis();
  29. long allTime = 0L;
  30. long endTime = 0L;
  31. InventoryProduct inventoryProduct = null;
  32. while (true) {
  33. if (allTime > 200){//如果超过了200ms,那就直接退出,然后从数据库中查询
  34. break;
  35. }
  36. try {
  37. inventoryProduct = inventoryProductBiz.loadInventoryProductCache(productId);
  38. if (inventoryProduct != null) {
  39. return inventoryProduct;
  40. } else {
  41. Thread.sleep(20);//如果查询不到就等20毫秒
  42. }
  43. endTime = System.currentTimeMillis();
  44. allTime = endTime - startTime;
  45. } catch (Exception e) {
  46. }
  47. }
  48. /**
  49. * 代码执行到这来,只有以下三种情况
  50. * 1、缓存中本来有数据,由于redis内存满了,redis通过LRU算法清除了缓存,导致数据没有了
  51. * 2、由于之前数据库查询比较慢或者内存太小处理不过来队列中的数据,导致队列里挤压了很多的数据,所以一直没有从数据库中获取数据然后插入到缓存中
  52. * 3、数据库中根本没有这样的数据,这种情况叫数据穿透,一旦别人知道这个商品没有,如果一直执行查询,就会一直查询数据库,如果过多,那么有可能会导致数据库瘫痪
  53. */
  54. inventoryProduct = inventoryProductBiz.loadInventoryProductByProductId(productId);
  55. if (inventoryProduct != null) {
  56. Request forcRrequest = new InventoryQueryCacheRequest(productId,inventoryProductBiz,true);
  57. requestAsyncProcessBiz.process(forcRrequest);//这个时候需要强制刷新数据库,使缓存中有数据
  58. return inventoryProduct;
  59. }
  60. return null;
  61. }
  62. }