专业的JAVA编程教程与资源

网站首页 > java教程 正文

JAVA常用组件Google Guava缓存Cache使用

temp10 2024-10-25 17:00:24 java教程 10 ℃ 0 评论

Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库。提供Cache本地缓存工具在高并发和日常使用中也有不错的效果。

提供 的缓存与JAVA本身ConcurrentMap非常相似,使用起来也非常顺手。增加的定时回收机制在很多场景下解决了很多麻烦,同时Guava Cache是在内存中缓存数据,相比较于数据库或redis存储,访问内存中的数据会更加高效。使用的时候可以根据业务的需要适当选择。

JAVA常用组件Google Guava缓存Cache使用

maven引用:

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

引入gradle依赖:

compile 'com.google.guava:guava:26.0-jre'

常用的方法如下:

public static Cache<String,Integer> googleCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.HOURS).maximumSize(20000).build();

public static void putCache(String key,Integer value){

googleCache.put(key, value);

}

public static boolean isInvalid(String key) throws ExecutionException{

boolean result = false;

Integer resultInt = googleCache.get(key,new Callable<Integer>() {

@Override

public Integer call() throws Exception {

return -1;

}

});

if(resultInt>0){

result = true;

}

return result;

}

public static Integer get(String key){

Integer resultInt=-1;

try {

resultInt = googleCache.get(key,new Callable<Integer>() {

@Override

public Integer call() throws Exception {

return -1;

}

});

} catch (ExecutionException e) {

e.printStackTrace();

}

return resultInt;

}

方法说明:

concurrencyLevel(int concurrencyLevel)-允许同时并发更新操作数

maximumSize(long size)-允许最大的缓存条目数

maximumWeight(long weight)-数据清除权重

weakKeys()-将缓存中的key设置成weakKey模式

initialCapacity(int initialCapacity)-指定用于缓存的hash table最低总规模

个别清除:Cache.invalidate(key)

批量清除:Cache.invalidateAll(keys)

清除所有缓存项:Cache.invalidateAll()

总结:

1:由于是在内存中操作,故不能持久化,使用时还要顾忌到这一点。

2:由于是使用系统内存,因此也意味着消耗系统的内存来换取读取性能的提升。

3:由于是单机访问数据,个别高并发下需要考虑集群处理。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表