Guava的使用

Guava 是什么?

  Guava是一种基于开源的Java库,其中包含谷歌正在由他们很多项目使用的很多核心库。这个库是为了方便编码,并减少编码错误。这个库提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方法。

Guava的好处

1、标准化 - Guava库是由谷歌托管。

2、高效 - 可靠,快速和有效的扩展JAVA标准库

3、优化 -Guava库经过高度的优化

guava可以设置key值大小,初始、最终容量,有LRU机制,满了之后根据LRU策略淘汰非热点数据

Guava Cache:可控制的大小和超时时间,可配置的LRU策略,线程安全

  本地热点缓存,有这么几个特点:

    热点数据,脏读特别不敏感,内存必须可控等

    本地缓存和redis缓存相比有何优点?快!可以节省网络传输的时间开销

实战:

  1、导包

<!--这个是补充的,redis也可以使用redisTemplate-->

<dependency>

扫描二维码关注公众号,回复: 7508902 查看本文章

      <groupId>org.springframework.session</groupId>

      <artifactId>spring-session-data-redis</artifactId>

      <version>2.0.5.RELEASE</version>

</dependency>

<!--这个是guava的包-->

    <dependency>

      <groupId>com.google.guava</groupId>

      <artifactId>guava</artifactId>

      <version>18.0</version>

    </dependency>

  2、编写接口:

//封装本地缓存操作类

public interface CacheService {

    //存方法

    void setCommonCache(String key,Object value);

    //取方法

    Object getFromCommonCache(String key);

}

  3、编写实现类

@Service

public class CacheServiceImpl implements CacheService {

    private Cache<String,Object> commonCache = null;

    @PostConstruct

    public void init(){

        commonCache = CacheBuilder.newBuilder()

                //设置缓存容器的初始容量为10

                .initialCapacity(10)

                //设置缓存中最大可以存储100个KEY,超过100个之后会按照LRU的策略移除缓存项

                .maximumSize(100)

                //设置写缓存后多少秒过期

                .expireAfterWrite(60, TimeUnit.SECONDS).build();

    }

    @Override

    public void setCommonCache(String key, Object value) {

            commonCache.put(key,value);

    }

    @Override

    public Object getFromCommonCache(String key) {

        return commonCache.getIfPresent(key);

    }

}

  4、项目中使用

@RequestMapping(value = "/get",method = {RequestMethod.GET})

@ResponseBody

public CommonReturnType getItem(@RequestParam(name = "id")Integer id){

        ItemModel itemModel = null;

        //先取本地缓存

        itemModel = (ItemModel) cacheService.getFromCommonCache("item_"+id);

        if(itemModel == null){

            //根据商品的id到redis内获取

            itemModel = (ItemModel) redisTemplate.opsForValue().get("item_"+id);

            //若redis内不存在对应的itemModel,则访问下游service

            if(itemModel == null){

                itemModel = itemService.getItemById(id);

                //设置itemModel到redis内

                redisTemplate.opsForValue().set("item_"+id,itemModel);

                redisTemplate.expire("item_"+id,10, TimeUnit.MINUTES);

            }

            //填充本地缓存

            cacheService.setCommonCache("item_"+id,itemModel);

        }

        ItemVO itemVO = convertVOFromModel(itemModel);

        return CommonReturnType.create(itemVO);

}

 

猜你喜欢

转载自www.cnblogs.com/blogofbin/p/11703685.html