本地缓存加redis缓存

本地热点缓存实现:

  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;
/**
 * 本地热点缓存业务层
 */
@Service
public class ICacheServiceImpl implements ICacheService {

      private Cache<String,Object> commonCache=null;
        @PostConstruct//在servlet加载时运行一次
      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);
    }
}
 
  
 
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;
        }
    }

猜你喜欢

转载自www.cnblogs.com/neona/p/13401879.html