欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

guava cache简单工具类 博客分类: javacache javacache 

程序员文章站 2024-03-18 19:03:10
...

1、pom文件中引入guava对应的jar

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

 

 2、GuavaCacheUtil

import java.math.BigDecimal;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
/**
 * guava本地缓存工具类
 * @author lh
 *
 */
public final class GuavaCacheUtil {
	
	private static CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().maximumSize(2000).initialCapacity(10);
	private static Cache<String, Object> cache;
	static{
		cache =cacheBuilder.build();
	}
	private GuavaCacheUtil() {
	}
	
	/**
	 * 添加缓存
	 * @param key
	 * @param value
	 */
	public static void set(String key, Object value){
		cache.put(key, value);
	}
	
	/**
	 * 删除缓存
	 * @param key
	 */
	public static void del(String key){
		cache.invalidate(key);
	}
	
	/**
	 * 根据key取得缓存对象
	 * @param key
	 * @return
	 */
	public static Object get(String key){
		return cache.getIfPresent(key);
	}
	
	public static String getStr(String key){
		return get(key).toString();
	}
	
	public static int getInt(String key){
		Object value = get(key);
		if(value instanceof Integer){
			return Integer.valueOf(value.toString());
		}
		return 0;
	}
	
	public static BigDecimal getBigDecimal(String key){
		Object value = get(key);
		if(value instanceof BigDecimal){
			return new BigDecimal(value.toString());
		}
		return BigDecimal.ZERO;
	}
	
	
}

 

相关标签: java cache