Guava Cache 创建

guava是谷歌几个java核心类库的集合,包括集合、缓存、原生类型、并发、常用注解、基本字符串操作和I/O等等。

 

这篇文章主要说明下其中缓存部分的用法。这文章主要是我结合wiki中内容学习的一个小结:

 

wiki的地址如下,但是需要fan qiang访问: https://code.google.com/p/guava-libraries/wiki/CachesExplained

 

基本上可以通过两种方式来创建cache:

 

cacheLoader

 

callable callback

 

通过这两种方法创建的cache,和通常用map来缓存的做法比,不同在于,这两种方法都实现了一种逻辑——从缓存中取key X的值,如果该值已经缓存过了,则返回缓存中的值,如果没有缓存过,可以通过某个方法来获取这个值。

 

但不同的在于cacheloader的定义比较宽泛,是针对整个cache定义的,可以认为是统一的根据key值load value的方法。

 

而callable的方式较为灵活,允许你在get的时候指定。

 

下面是两种方法的例子:

 

首先是基于cacheloader的方法

 

    @Test
    public void testCacheBuilder() throws ExecutionException {

        LoadingCache<String, String> graphs = CacheBuilder.newBuilder().maximumSize(1000)
                .build(new CacheLoader<String, String>() {
                    public String load(String key) {
                        // 这里是key根据实际去取值的方法,例如根据这个key去数据库或者properties文件中取值
                        ApplicationContext context = new FileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");
                        JdbcCustomerDAO aJdbcCustomerDAO = context.getBean(JdbcCustomerDAO.class);

                        System.out.println("load method has been invoked");
                        return aJdbcCustomerDAO.findValue(key);
                    }
                });

        String resultVal = graphs.get("testKey");
        System.out.println("first time value is: " + resultVal);

        String resultVal1 = graphs.get("testKey");
        System.out.println("second time values is: " + resultVal1);

    }

 其次是基于实现callable的方法:

@Test
    public void testCallable() throws ExecutionException {
        // 没有使用CacheLoader
        Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();

        String resultVal = cache.get("testKey", new Callable<String>() {
            public String call() {
                // 这里先根据key实际去取值的方法,例如根据这个key去数据库或者properties文件中取值
                ApplicationContext context = new FileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");
                JdbcCustomerDAO aJdbcCustomerDAO = context.getBean(JdbcCustomerDAO.class);

                System.out.println("resultVal call method is invoked");
                return aJdbcCustomerDAO.findValue("testKey");
            }
        });
        System.out.println("first time value is: " + resultVal);

        String resultVal1 = cache.get("testKey", new Callable<String>() {
            public String call() {
                // 这里先根据key实际去取值的方法,例如根据这个key去数据库或者properties文件中取值
                ApplicationContext context = new FileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");
                JdbcCustomerDAO aJdbcCustomerDAO = context.getBean(JdbcCustomerDAO.class);

                System.out.println("resultVal1 call method is invoked");
                return aJdbcCustomerDAO.findValue("testKey");
            }
        });
        System.out.println("second time values is: " + resultVal1);
    }
 
Guava Cache是Google提供的一套Java工具包中的一部分,它是一套非常完善的本地缓存机制(JVM缓存)。它的设计灵感来源于ConcurrentHashMap,可以按照多种策略来清理存储在其中的缓存值,同时保持很高的并发读写性能。在使用Guava Cache时,可以通过get()或者put()等方法进行缓存操作,当进行这些操作时,Guava Cache会进行惰性删除,即在获取或者放置缓存的时候判断缓存是否过期并进行删除。在Guava Cache的核心原理中,使用Segment来进行缓存值的定位和管理。在创建Guava Cache对象时,可以使用CacheLoader来自动加载数据到缓存中,当缓存不存在时,CacheLoader会负责获取数据并将其放置到缓存中。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [[由零开始]Guava Cache介绍和用法](https://blog.csdn.net/qq497811258/article/details/108260969)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Guava Cache简介、应用场景分析、代码实现以及核心的原理](https://blog.csdn.net/weixin_44795847/article/details/123702038)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值