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缓存使用的更多相关文章

  1. Guava缓存器源码分析——删除消息

    Guava缓存器的删除消息机制 测试代码——             LoadingCache<String, Integer> cache = CacheBuilder.newBuild ...

  2. Guava缓存器源码分析——缓存统计器

    Guava缓存器统计器实现: 全局统计器——         1.CacheBuilder的静态成员变量Supplier<StatsCounter> CACHE_STATS_COUNTER ...

  3. guava缓存底层实现

    摘要 guava的缓存相信很多人都有用到, Cache<String, String> cache = CacheBuilder.newBuilder() .expireAfterWrit ...

  4. Google Guava缓存实现接口的限流

    一.项目背景 最近项目中需要进行接口保护,防止高并发的情况把系统搞崩,因此需要对一个查询接口进行限流,主要的目的就是限制单位时间内请求此查询的次数,例如1000次,来保护接口. 参考了 开涛的博客聊聊 ...

  5. springboot集成Guava缓存

    很久没有写博客了,这段时间一直忙于看论文,写论文,简直头大,感觉还是做项目比较舒服,呵呵,闲话不多说,今天学习了下Guava缓存,这跟Redis类似的,但是适用的场景不一样,学习下吧.今天我们主要是s ...

  6. spring中添加google的guava缓存(demo)

    1.pom文件中配置 <dependencies> <dependency> <groupId>org.springframework</groupId> ...

  7. guava缓存设置return null一直报错空指针

    guava缓存设置return null一直报错空指针 因为缓存不允许返回为空

  8. spring boot使用guava缓存

    1.pom中插入依赖: <!--guava缓存cache--> <dependency> <groupId>com.google.guava</groupId ...

  9. guava缓存批量获取的一个坑

    摘要 Guava Cache是Google开源的Java工具集库Guava里的一款缓存工具,一直觉得使用起来比较简单,没想到这次居然还踩了一个坑 背景 功能需求抽象出来很简单,就是将数据库的查询sth ...

  10. guava缓存第一篇

    guava缓存主要有2个接口,Cache和LoadingCache. Cache,全类名是com.google.common.cache.Cache,支持泛型.Cache<K, V>. L ...

随机推荐

  1. Centos7下安装破解confluence6.3

    confluence是一个专业的企业知识管理与协同软件,可以用于构建企业wiki.通过它可以实现团队成员之间的协作和知识共享.现在大多数公司都会部署一套confluence与jira的结合,用作内部w ...

  2. .net mvc禁用浏览器缓存

    我正在寻找方法来禁用 整个 ASP.Net MVC 网站 的浏览器缓存 我发现以下方法, Response.Cache.SetCacheability(System.Web.HttpCacheabil ...

  3. mvc controller放目录里面该怎么办?

    方法一,可以在目录中命名一个和目录同样名字的controller,然后用特性来进行设置,比如: Controllers/myfolder/myfolderController.cs 我建立了上述结构, ...

  4. destoon 部署到服务器如何修改密码使网站能正常访问登录

    1.根目录的config.inc.php  修改 db_pass 2.缓存文件 根目录/file/cache/module-2.php   修改 uc_dbpwd PS:不一定都在module-2.p ...

  5. 转:西部数据NAS设备hack

    通过该文学习一下常见硬件web漏洞.重点关注一下几个方面: 1.登录验证代码: 2.文件上传代码: 3.system/exec/popen等是否存在注入可能: 4.调用二进制文件: 5.未登陆可以访问 ...

  6. (7) go 函数

    1.格式 调用 2.包 (1)包 本质 文件夹.每一个文件都必须属于一个包 (2)给包取别名 (3)函数的首字母大小,决定是否能被外包访问 (3) 3.多返回值 4.递归 5.基本数据类型和数组都是拷 ...

  7. 运行时候报异常could only be replicated to 0 nodes instead of minReplication (=1). There are 2 datanode(s) running and no node(s) are excluded in this operation.

    运行时候报异常could only be replicated to 0 nodes instead of minReplication (=1).  There are 2 datanode(s) ...

  8. 【BZOJ 1036】【ZJOI 2008】树的统计Count

    http://www.lydsy.com/JudgeOnline/problem.php?id=1036 复习了一下好写好调的lct模板啦啦啦--- #include<cstdio> #i ...

  9. 浅谈OI中的提交答案

    在OI中,题目有三类: 传统题 交互题 提交答案题 今天来了解一下第三类 概述 传统题:给你一个题面,你需要交一个程序,评测姬会用你的程序运行你看不到的一些测试点,用输出和正确答案比较 提交答案题:给 ...

  10. 【找规律】【递归】XVII Open Cup named after E.V. Pankratiev Stage 4: Grand Prix of SPb, Sunday, Octorber 9, 2016 Problem F. Doubling

    题意: 给你一个n,问你R(n)对应的字符串长度最小的是啥. dp打个表出来,f(i)表示i值对应的字符串的最小长度,发现f(1)=1,f(2)=2,其他的情况下,若是偶数,则恰好在其外面加一对中括号 ...