Google Guava Cache 示列

google guava cache

引用maven依赖
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>
java代码
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhengyong on 16/10/9.
 */
public class GuavaCacheTest {

    private static LoadingCache<String, String> graphs = null;

    public static void main(String[] args) {
        loadDataToCache();
        // 第一次从数据源获取,并缓存
        String value1 = getValue("mykey");
        // 第二次从缓存获取
        String value2 = getValue("mykey");
        // 过期重新从数据源加载进缓存
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String value3 = getValue("mykey");
        String value4 = getValue("mykey");
        String value5 = getValue("mykey2");
        String value6 = getValue("mykey2");
    }

    /**
     * 根据key获取值
     * 
     * @param key 查询条件key
     * @return 返回value值
     */
    private static String getValue(String key) {
        String resultVal = null;
        try {
            resultVal = graphs.get(key);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(String.format("get key=%s return value=%s", key, resultVal));
        return resultVal;
    }

    /**
     * 声明加载数据源方式
     */
    private static void loadDataToCache() {

        graphs = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(10, TimeUnit.MILLISECONDS).build(new CacheLoader<String, String>() {

          public String load(String key) {
              // 这里是key根据实际去取值的方法
              System.out.println(String.format("load '%s' from database...",
                                               key));
              return "value_" + key;
          }
      });
    }
}
运行结果
load 'mykey' from database...
get key=mykey return value=value_mykey
get key=mykey return value=value_mykey
load 'mykey' from database...
get key=mykey return value=value_mykey
get key=mykey return value=value_mykey
load 'mykey2' from database...
get key=mykey2 return value=value_mykey2
get key=mykey2 return value=value_mykey2
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhengyong15984285623/article/details/52769537
文章标签: 谷歌 cache
个人分类: guava
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭