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); } }