分级缓存之项目本地热点缓存加redis缓存

分级缓存

  • 第一级缓存:项目JVM本地内存(本地热点缓存)
  • 第二级缓存:Redis缓存
  • 第三级缓存:数据库


本地热点缓存实现:
要使用的是Guava cache组件

  guava是开源java 库。是由谷歌公司研发。 这个库主要是为了方便编码,并且减少编码错误。 这个库用于集合 缓存 并发性 常用注解 字符串处理呀 i/o 和 验证 实用的方法。

 1.引入pom引入guava

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>

 

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;





/**
 * 本地缓存接口
 */
public interface ICacheService {
    /**
     * 存
     */
    public void setCommonCache(String key,Object value);

    /**
     * 取
     */
    public Object getCommonCache(String key);
}

 

/**
 * 本地热点缓存业务层
 */
@Service
public class ICacheServiceImpl implements ICacheService {

      private Cache<String,Object> commonCache=null;
        @PostConstruct//在servlet加载时运行一次,修饰非静态void方法,java的注解。运行顺序:构造方法,依赖注入,注解方法
      public void init(){
          commonCache= CacheBuilder.newBuilder()
                  .initialCapacity(10)//缓存初始容量为10
                  .maximumSize(100)//最大可存储100个key,通过LRU算法不常用移除
                  .expireAfterWrite(60, TimeUnit.SECONDS)//设置写缓存多久过期
                  .build();
      }

    /**
     * 存缓存
      * @param key
     * @param value
     */
    @Override
    public void setCommonCache(String key, Object value) {
            commonCache.put(key,value);
    }

    /**
     * 取缓存
     * @param key
     * @return
     */
    @Override
    public Object getCommonCache(String key) {
        return commonCache.getIfPresent(key);
    }
}

 

@Resource
private ICacheService iCacheService;
public SeckillGoodsDetailVo findByid(Integer id) {
        //查本地缓存
        SeckillGoodsDetailVo commonCache = (SeckillGoodsDetailVo) iCacheService.getCommonCache(SeckillGoodsKey.goodsiddetail.getPrefix() + id);
        //本地缓存为空
        if (commonCache == null) {
            //查redis缓存
            String seckillGoods = stringRedisTemplate.opsForValue().get(SeckillGoodsKey.goodsiddetail.getPrefix() + id);
            //redis为空
            if (StringUtils.isEmpty(seckillGoods)) {
          //查数据库 SeckillGoodsDetailVo byid
= seckillGoodsDetailVoMapper.findByid(id);
          //转成字符串 seckillGoods
= JSON.toJSONString(byid); //存redis缓存 stringRedisTemplate.opsForValue().set(SeckillGoodsKey.goodsiddetail.getPrefix() + id, seckillGoods); //存本地热点缓存 iCacheService.setCommonCache(SeckillGoodsKey.goodsiddetail.getPrefix() + id, byid); return byid; } else { commonCache = JSON.parseObject(seckillGoods, SeckillGoodsDetailVo.class); //存本地热点缓存 iCacheService.setCommonCache(SeckillGoodsKey.goodsiddetail.getPrefix() + id, commonCache); return commonCache; } } else { return commonCache; } }

 

posted @ 2020-07-30 09:11  neona  阅读(499)  评论(0编辑  收藏  举报