使用Google Guava实现定时缓存功能

使用Google Guava实现定时缓存功能

一:加入maven依赖

<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>19.0</version></dependency>

二:使用缓存

方法一:

package com.test.guava;import java.util.concurrent.TimeUnit;import com.google.common.cache.Cache;import com.google.common.cache.CacheBuilder;public class UserService{private final Cache<String, String> cache;public UserService(){/** * 5秒自动过期 */cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build();}public String getUserName(String id) throws Exception{return cache.get(id, () -> {System.out.println("method invoke2");//这里执行查询数据库,等其他复杂的逻辑return "User:" + id;});}}

方法二:
package com.test.guava;import java.util.concurrent.TimeUnit;import com.google.common.cache.CacheBuilder;import com.google.common.cache.CacheLoader;import com.google.common.cache.LoadingCache;public class UserService{private final LoadingCache<String, String> cache;public UserService(){/** * 5秒自动过期 */cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build(new CacheLoader<String, String>() {    public String load(String id) throws Exception    {    System.out.println("method inovke");    //这里执行查询数据库,等其他复杂的逻辑            return "User:" + id;    }    });}public String getUserName(String id) throws Exception{return cache.get(id);}}

三:测试代码:
package com.test.guava;import java.util.concurrent.TimeUnit;public class GuavaCacheTest{public static void main(String[] args)throws Exception{UserService us = new UserService();for(int i=0;i<20;i++){System.out.println(us.getUserName("1001"));TimeUnit.SECONDS.sleep(1);}}}

执行测试代码,输出如下:

推荐阅读