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安装私有gitlab

    1.安装依赖包 yum install -y curl policycoreutils openssh-server openssh-clients postfix systemctl start p ...

  2. ubuntu安装过程记录

    [DNS修改] 新下载的ubuntu 17.04 安装后DNS是指向谷歌DNS的,谷歌被屏蔽啦,所以无法解析域名.解决办法: ctrl+alt+t 启动终端 : sudo su  输入管理員密碼,或去 ...

  3. python之sqlite3使用详解

    Python SQLITE数据库是一款非常小巧的嵌入式开源数据库软件,也就是说没有独立的维护进程,所有的维护都来自于程序本身.它使用一个文件存储整个数据库,操 作十分方便.它的最大优点是使用方便,功能 ...

  4. Codeforces 1082 C. Multi-Subject Competition-有点意思 (Educational Codeforces Round 55 (Rated for Div. 2))

    C. Multi-Subject Competition time limit per test 2 seconds memory limit per test 256 megabytes input ...

  5. Java Eclipse插件

    EasyExplore 快速打开文件所在目录1 http://sourceforge.net/projects/easystruts/ OpenExplorer 快速打开文件所在目录2 https:/ ...

  6. 一个Bean属性拷贝的工具类

    package com.fpi.spring.qaepb.cps.util; import java.beans.IntrospectionException; import java.beans.P ...

  7. run()和start()的区别

    run没有启新的线程,start方法才会调用Thread的native的start0方法,start0会调用run方法,开启新的线程,博主这么做,不是多线程顺序执行,而是把业务阻塞在主线程里.请打印: ...

  8. 【hihoCoder 第133周】【hihoCoder 1467】2-SAT·hihoCoder音乐节

    http://hihocoder.com/problemset/problem/1467 2-sat模板...详细的题解请看题目里的提示. tarjan模板打错again致命伤qwq #include ...

  9. [Codeforces #196] Tutorial

    Link: Codeforces #196 传送门 A: 枚举 #include <bits/stdc++.h> using namespace std; #define X first ...

  10. ubuntu16 安装docker

    本文开发环境为Ubuntu 16.04 LTS 64位系统,通过apt的docker官方源安装最新的Docker CE(Community Edition),即Docker社区版,是开发人员和小型团队 ...