博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【商城】redis分布式多级缓存应用(瓶颈之殇)
阅读量:4119 次
发布时间:2019-05-25

本文共 3353 字,大约阅读时间需要 11 分钟。

多级缓存

应用场景:我们知道redis的tps读写能力在10w/s左右,在大促或者双11场景,很多商品的访问高达百万千万级别,如果只使用redis缓存,是不能满足业务需要。

缓存混合存在问题

基于以上场景,我们需要使用多级缓存实现,利用本地缓存与redis缓存来实现:

  1. 本地缓存 ,使用ehcache来实现,ehcache作为JVM级别的缓存,不能够保证分布式集群部署一致性,无法实现分布式场景下缓存共享;
  2. 本地缓存和分布式redis缓存如何混合使用;

sboot代码实现

(1) 配置文件配置, ehcache.xml网上有很多配置,可以根据实际需要配置

#encache 本地缓存
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml

(2) Springboot开启Config配置

/
**

  • @author libiao

  • 开启本地缓存EnableCaching扫描spring.cache.ehcache.config

    */
    @Configuration
    @EnableCaching
    public class CacheConfig {
    @Resource
    private CacheManager cacheManager;

    /**

    • ehcache缓存处理
    • @return
    • @throws Exception
      */
      @Bean(“ehcache”)
      public Cache initEhcache()throws Exception{
      return cacheManager.getCache(“userCache”);
      }
      }

(3) 业务代码

//1、 从本地缓存获取
Product product = ehcache.get(Constants.CACHE_PRODUCT_PREFIX + productId, Product.class);
if (product != null){
return product;
}
//2、从redis缓存获取
product = redis.get(Constants.CACHE_PRODUCT_PREFIX + productId, Product.class);
if (product != null){
return product;
}
//3、增加商品的zk路径监控,如下所示;

本地缓存一致性保证

本地缓存使用zookeeper保证,针对当前商品添加zk的path,如果商品信息发生变更通过zk的watch机制进行淘汰本地缓存

String zkMonitorProductPath = Constants.getZkMonitorProductPath(productId);

if (zooKeeper.exists(zkMonitorProductPath,true) == null){
//路径不存在,则创建路径,状态为true
zooKeeper.create(zkSoldOutProductPath, “true”.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
//监听zk节点某个商品状态
zooKeeper.exists(zkSoldOutProductPath, true);

@Beanpublic ZooKeeper initZookeeper()throws Exception{    ZookeeperWatcher zkWatcher = new ZookeeperWatcher();    ZooKeeper zooKeeper = new ZooKeeper(zookeeperAddress, 30000, zkWatcher);    zkWatcher.setZooKeeper(zooKeeper);    zkWatcher.setCache(cache);  //见上cache配置    return zooKeeper;}/**zk淘汰本地缓存*/public class ZookeeperWatcher implements Watcher {private ZooKeeper zooKeeper;private Cache cache;public void setZooKeeper(ZooKeeper zooKeeper, Cache cache){    this.zooKeeper = zooKeeper;    this.cache = cache;}@Overridepublic void process(WatchedEvent event) {    if (event.getType() == Event.EventType.None && event.getPath() == null){        log.info("zookeeper connected success!");        //创建zk的商品标记根节点        try{            //App启动时候创建标记root节点ZK_PRODUCT_MONITOR_FLAG            if (zooKeeper.exists(Constants.ZK_PRODUCT_MONITOR_FLAG, false) == null){                //创建根节点,无数据                zooKeeper.create(Constants.ZK_PRODUCT_SOLD_OUT_FLAG, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);            }        }catch (Exception e){            log.error("商品标记失败", e);        }    }else if (event.getType() == Event.EventType.NodeDataChanged){        //zk目录节点数据变化通知事件        try{            String path = event.getPath();            if (path.startsWith(Constants.ZK_PRODUCT_MONITOR_FLAG)) {                String monitorFlag = new String(zooKeeper.getData(path, true, new Stat()));                log.info("zookeeper 数据节点修改变动,path:{},value:{}", path, monitorFlag );                if (Constants.ZK_FALSE.equals(monitorFlag )) {                    String productId = path.substring(path.lastIndexOf("/") + 1);                                        cache.evict(Constants.ZK_PRODUCT_MONITOR_FLAG+productId);                    log.info("清除商品{}本地内存", productId);                }            }        }catch (Exception e){            log.error("zookeeper数据节点修改回调事件异常", e);        }    }}

}

转载地址:http://cccpi.baihongyu.com/

你可能感兴趣的文章
X-code beta 开发iWatch项目,运行没有错误,但是某些操作一点就崩,而且找不错误的原因场景一
查看>>
Xcode 报错: Extra argument in call
查看>>
iTunes Connect 上传APP报错: Communication error. please use diagnostic mode to check connectivity.
查看>>
#import <Cocoa/Cocoa.h> 报错 Lexical or Preprocessor Issue 'Cocoa/Cocoa.h' file not found
查看>>
`MQTTClient (~> 0.2.6)` required by `Podfile`
查看>>
X-Code 报错 ld: library not found for -lAFNetworking
查看>>
Bitcode
查看>>
If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
查看>>
为什么新手也要学习微服务架构设计?
查看>>
专题 | 如何抢先一步拿 Offer?
查看>>
那些拿到腾讯、阿里等大厂offer的人,都有这个共同点
查看>>
陆奇、雷军、熊晓鸽聊疫情后的创业风口
查看>>
卖掉 3000 平房子,50 岁程序员回国写代码,三个月内融资 2000 万美元
查看>>
15 岁黑进系统,发挑衅邮件意外获 Offer,不惑之年捐出全部财产,Twitter CEO 太牛了!...
查看>>
一行 Python 代码能实现什么丧心病狂的功能? | CSDN博文精选
查看>>
国士无双:卖掉美国房子,回国创办姚班,他只为培养一流的程序员!
查看>>
面试细节:为什么 HashMap 默认加载因子非得是0.75?
查看>>
7.20草稿(先别发)
查看>>
蚂蚁金服上市估值2k亿美金!会开发到底有多吃香?
查看>>
美国 AI 博士一针见血:Python 这样学最容易成为高手!
查看>>