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

一:加入maven依赖


	com.google.guava
	guava
	19.0

二:使用缓存

方法一:

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 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 cache;
	
	public UserService()
	{
		/**
		 * 5秒自动过期
		 */
		cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build(new CacheLoader() {
    		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);
		}
	}
}

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

使用Google Guava实现定时缓存功能_第1张图片

你可能感兴趣的:(Java)