guava---缓存

你说的曾经没有我的故事 提交于 2020-03-13 06:24:39

guava的缓存使用方式:

  •  先不解释为什么用guava,以及guava的缓存原理
  • 主要介绍如何使用?

     缓存花样怎么变化,无非就是创建一个缓存容器,put数据,get数据;

     guava中有两种创建缓存的方式, loadingCache 和 Cache Callable 。

    从实现使用层面来说,最大的区别就是Callable可以直接定义数据不存在的时候该如何取;Loading需要实现一个get方法去实现。

 

public class App

{
    public static Cache<String, String> cache2 = CacheBuilder.newBuilder().build();

    public static String get(String key) throws ExecutionException {
        String var = cache2.get(key, new Callable<String>() {
            /**
             * 设置了没有读取到值得时候执行策略
             * @return
             * @throws Exception
             */
            public String call() throws Exception {
                System.out.println("如果没有值就去读数据库");
                //
                String var = "从库中读取数据";
                return var;
            }

        });
        return var;
    }

    public static LoadingCache<String, String> cacheBulider = CacheBuilder.newBuilder().build(
            new CacheLoader<String, String>() {
                @Override
                public String load(String key) throws Exception {
                    String value = "读取数据库" + "=====" + key;
                    return value;
                }
            }
    );


    public static void main(String[] args) throws ExecutionException {

        System.out.println("Cache callable 方式");
        String v1 = cacheBulider.get("zl");
        System.out.println(v1);
        cacheBulider.put("zl", "test");
        v1 = cacheBulider.get("zl");
        System.out.println(v1);
        System.out.println(" Loading cache 方式");
        v1 = get("zl");
        System.out.println(v1);
        cache2.put("zl", "test1");
        v1 = get("zl");
        System.out.println(v1);


    }
}

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!