Guava缓存使用
public class GuavaCache {
/**
* LoadingCache当缓冲中不存在时,可自动加载
* */
private static LoadingCache<Integer,Student> studentCache = CacheBuilder.newBuilder()
/**
* 设置写入缓存后过期时间(8秒过期)
* */
.expireAfterWrite(8, TimeUnit.SECONDS)
/**
* 使用SoftReference封装value,当内存不足时,自动回收
* */
.softValues()
/**
* 设置缓存初始化容量
* */
.initialCapacity(100)
/**
* 设置缓存对象权重
* */
.weigher(new Weigher<Integer, Student>() {
@Override
public int weigh(Integer key, Student value) {
return key % 2 == 0 ? 1 : 0;
}
})
/**
* 统计缓存命中率
* */
.recordStats()
/**
* 定义缓存对象失效的时间精度位纳秒级
* */
.ticker(Ticker.systemTicker())
/**
* 设置缓存移除通知
* */
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
System.out.println((Integer) notification.getKey() + " was removed , " +
"cause is " + notification.getCause());
}
})
/**
* build方法指定CacheLoader,实现数据自动加载
* */
.build(new CacheLoader<Integer, Student>() {
@Override
public Student load(Integer key) throws Exception {
Student st = new Student();
st.setStudentNo(key);
return st;
}
});
/**
* Cache.get(key, Callable)
* 当缓存中不存在key对应缓存对象时,调用Callable获取
* */
public static final Student getStudent(Integer key) throws ExecutionException {
try {
return studentCache.get(key, new Callable<Student>() {
@Override
public Student call() throws Exception {
Student st = new Student();
st.setStudentNo(key);
return st;
}
});
} finally {
System.out.println("Cache hit stats : " + studentCache.stats().toString());
}
}
public static final void testStudentCache() throws ExecutionException, InterruptedException {
for (int i = 0; i < 20; ++i) {
Student student = studentCache.get(i);
System.out.println(student);
TimeUnit.SECONDS.sleep(1);
}
System.out.println("Cache hit stats : " + studentCache.stats().toString());
}
public static final void testConcurrentStudentCache(int threadNumber) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(100);
Random random = new Random();
ExecutorService es = Executors.newFixedThreadPool(threadNumber);
for (int i = 0; i < 200; ++i) {
es.execute(new Runnable() {
@Override
public void run() {
try {
studentCache.get(random.nextInt(20));
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
});
}
latch.await();
es.shutdown();
System.out.println("Cache hit stats : " + studentCache.stats().toString());
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
// GuavaCache.testStudentCache();
GuavaCache.getStudent(1);
GuavaCache.getStudent(1);
}
}
Guava缓存使用的更多相关文章
- Guava缓存器源码分析——删除消息
Guava缓存器的删除消息机制 测试代码—— LoadingCache<String, Integer> cache = CacheBuilder.newBuild ...
- Guava缓存器源码分析——缓存统计器
Guava缓存器统计器实现: 全局统计器—— 1.CacheBuilder的静态成员变量Supplier<StatsCounter> CACHE_STATS_COUNTER ...
- guava缓存底层实现
摘要 guava的缓存相信很多人都有用到, Cache<String, String> cache = CacheBuilder.newBuilder() .expireAfterWrit ...
- Google Guava缓存实现接口的限流
一.项目背景 最近项目中需要进行接口保护,防止高并发的情况把系统搞崩,因此需要对一个查询接口进行限流,主要的目的就是限制单位时间内请求此查询的次数,例如1000次,来保护接口. 参考了 开涛的博客聊聊 ...
- springboot集成Guava缓存
很久没有写博客了,这段时间一直忙于看论文,写论文,简直头大,感觉还是做项目比较舒服,呵呵,闲话不多说,今天学习了下Guava缓存,这跟Redis类似的,但是适用的场景不一样,学习下吧.今天我们主要是s ...
- spring中添加google的guava缓存(demo)
1.pom文件中配置 <dependencies> <dependency> <groupId>org.springframework</groupId> ...
- guava缓存设置return null一直报错空指针
guava缓存设置return null一直报错空指针 因为缓存不允许返回为空
- spring boot使用guava缓存
1.pom中插入依赖: <!--guava缓存cache--> <dependency> <groupId>com.google.guava</groupId ...
- guava缓存批量获取的一个坑
摘要 Guava Cache是Google开源的Java工具集库Guava里的一款缓存工具,一直觉得使用起来比较简单,没想到这次居然还踩了一个坑 背景 功能需求抽象出来很简单,就是将数据库的查询sth ...
- guava缓存第一篇
guava缓存主要有2个接口,Cache和LoadingCache. Cache,全类名是com.google.common.cache.Cache,支持泛型.Cache<K, V>. L ...
随机推荐
- VS2013 打开项目时提示This project is incompatible with the current edition Visual Studio.
刚安装完成了Visual Studio 2013后,打开项目时,遇到以下问题 解决方法:在Visual Studio 2013 的菜单中打开“Tools",并打开“Extensions an ...
- 编译 Windows 版本的 Unity Mono(2017-03-12 20:59)
上一篇说了如何编译 Android 下的 mono,这里简要说下编译 windows 版本的 mono,就是 mono.dll,Unity 版本只有一个 mono.dll,官方的 mono,好几个可执 ...
- sql 预编译 in
sql : "select * from json where id in (:paramName)"; 在使用Hibernate时,sql in的预编译语句为query.setP ...
- Python 头文件和常用函数
#coding=utf-8 """ @version: ?? @author: Donny @Mail: wdm666666@gmail.com @license: La ...
- Redux 洋葱模型理解
下面的代码会输出: A middleware1 开始C middleware2 开始E middleware3 开始======= G =======F middleware3 结束D middlew ...
- BZOJ 1257 [CQOI2007]余数之和sum(分块)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1257 [题目大意] 给出正整数n和k,计算j(n,k)=k mod 1 + k mod ...
- (1)CorePlot配置
先来看一下官方的说法,贴内容(https://code.google.com/p/core-plot/wiki/UsingCorePlotInApplications) Dependent Proje ...
- [NOIp2017提高组]列队
[NOIp2017提高组]列队 题目大意 一个\(n\times m(n,m\le3\times10^5)\)的方阵,每个格子里的人都有一个编号.初始时第\(i\)行第\(j\)列的编号为\((i-1 ...
- 输入sql语句,将结果写入到xml文件
import java.io.FileOutputStream; import java.sql.Connection; import java.sql.DriverManager; import j ...
- Activity(活动)生命周期(2)--活动状态
每个活动在其生命周期中最多会有4种状态 一.运行状态 当一个活动位于返回栈的栈顶的时候,这时活动就处于运行状态.系统一般不会回收,因为这会带来非常差的用户体验 二.暂停状态 当一个活动不处于栈顶状态的 ...