---
title: "com.google.common.cache.CacheLoader 本地緩存的使用方法"
author: "liumayulingyan"
date: "2014-06-19T13:58:02Z"
tags: []
categories: ["行业应用"]
slug: "com-google-common-cache-cacheloader"
draft: false
lastmod: "2014-06-19T13:58:02Z"
id: 2082544
url: "https://liumayulingyan.iteye.com/blog/2082544"
---

[http://blog.sina.com.cn/s/blog\_a2ec891e0101a20v.html](http://blog.sina.com.cn/s/blog_a2ec891e0101a20v.html)

 

 

package com.taobao.ju.my.common.biz.manager.impl;

 

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.TimeUnit;

 

import com.google.common.cache.Cache;

import com.google.common.cache.CacheBuilder;

import com.google.common.cache.CacheLoader;

import com.google.common.cache.LoadingCache;

 

public class LoadingCacheDemo {

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

//方法一

//创建本地缓存，当本地缓存不命中时，调用load方法，返回结果，再缓存结果。

LoadingCache loadingCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).maximumSize(10000).build(new CacheLoader() {

@Override

public String load(String key) throws Exception {

return getString(key);

}

});

 

loadingCache.get("test");

loadingCache.get("test2");

//方法二

//创建缓存对像

Cache cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).maximumSize(10000).build();

 

//调用缓存中的get方法，当缓存命中时直接返回结果，当不命中时，通过给定的Callable类call方法 返回结果，再缓存。这个方法

//到更灵活，可以用一个cache对象缓存多种不同的数据，只要用不同的Callable对象就行。

cache.get("111", new Callable() {

@Override

public String call() throws Exception {

System.out.println("经过 call()");

return "value.";

}

});

 

cache.get("222", new Callable() {

@Override

public String call() throws Exception {

System.out.println("经过 call()");

return "value.";

}

});

}

 

public static String getString(String key) {

System.out.println("经过 getString()");

return key + "--Test";

}

}