1. Spring local cache   【Spring 本地缓存】

Spring provided cacheable annotation since 3.1. It's very super convinient to use and can obviously boost application performance.

从3.1版本开始,Spring提供了cacheable注解。它使用起来非常方便,还可以很明显的提升应用性能。具体的,怎么使用呢?

First, create a cache bean.

首先,创建缓存bean。这里,我们设置一个三秒的本地缓存(写后3秒过期)。

@Beanpublic Cache ephemeralCache() {    return new ConcurrentMapCache(EPHEMERAL_CACHE, CacheBuilder.newBuilder()            .expireAfterWrite(3, TimeUnit.SECONDS)            .build().asMap(), false);}

Second, add @Cacheable to the existed method.

接下来,给想要使用缓存的已有方法加上@Cacheable注解

@Cacheable(cacheNames = AppCacheConfig.EPHEMERAL_CACHE, key = "{#root.methodName, 'test'}")public Integer genId() {    int i = ai.incrementAndGet();    System.out.println(String.format("populate cache %s", LocalDateTime.now()));    return i;}

Finally, enjoy!

然后,尽情体验缓存带来的快乐!

ExecutorService exe = Executors.newWorkStealingPool();exe.submit(() -> {    while (true) {        cacheApi.genId();        Thread.sleep(50);    }});

See output of below codes

下面的日志和最初的缓存设定完全吻合

2017-06-08 10:17:49.990  INFO 12460 --- [           main] com.loops.nbs.Application                : Started Application in 7.42 seconds (JVM running for 7.973)
populate cache 2017-06-08T10:17:52.372
populate cache 2017-06-08T10:17:55.379
populate cache 2017-06-08T10:17:58.387
populate cache 2017-06-08T10:18:01.394
populate cache 2017-06-08T10:18:04.402
populate cache 2017-06-08T10:18:07.409
populate cache 2017-06-08T10:18:10.417
populate cache 2017-06-08T10:18:13.426

2. Guava cache  【Guava 本地缓存】

Guava is a set of libraries provided by Google. In memory cache is part of it.

Guava是Google提供的一套工具库。这里只讨论其中的缓存部分。

public class GuavaCacheExample {
    static Cache<Integer, Integer> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(2, TimeUnit.SECONDS)
            .recordStats()
            .build();

    static LoadingCache<Integer, Integer> loadingCache = CacheBuilder.newBuilder()
            .expireAfterWrite(2, TimeUnit.SECONDS)
            .build(new CacheLoader<Integer, Integer>() {
                @Override
                public Integer load(Integer key) throws Exception {
                    System.out.println("populate cache");
                    return key * 10;
                }
            });

    static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) throws Exception {
        useNormalCache();
    }

    static void useNormalCache() throws Exception {
        scheduler.scheduleWithFixedDelay(() -> System.out.println(cache.stats()), 0, 1, TimeUnit.SECONDS);
        for (int i = 0; i < 10; i++) {
            System.out.println(cache.get(0, () -> {
                Thread.sleep(500);
                return 10;
            }));
            Thread.sleep(300);
        }
    }

    static void useLoadingCache() throws Exception {
        for (int i = 0; i < 10; i++) {
            System.out.println(loadingCache.get(1));
            Thread.sleep(300);
        }
    }
}

Usually, there are 2 types of caches

1) Cache

Cache is basic usage, it provides method to get and put cache.

Cache是基础用法,提供了get和put的操作。

2) LoadingCache

Loading cache requires a CacheLoader when cache is created. Every time when cache is expired or nonexisted, the load method will be called automatically and generate cache.

So user doesn't have to manually put cache back after cache is expired.

Loading cache在创建的时候需要给定 CacheLoader。如果缓存过期或者不存在,CacheLoader 的 load 方法就会被调用到并产生缓存。这样,用户就不用去关心那些过期的缓存项了。

Besides, we can add recordStats() when creating a cache object. Later we can monitor the cache usage by calling cache.stats()

Cache is created twice during the test, correspondingly, totalLoadTime (mesured in nano seconds) changed twice.

除此,我们还可以在创建缓存时使用 recordStats 来记录缓存的使用情况。之后用 cache 的 stats() 方法来观察。

测试过程中,我们的缓存产生了2次,totalLoadTime (纳秒为单位)也很好的佐证了这一点。

CacheStats{hitCount=0, missCount=0, loadSuccessCount=0, loadExceptionCount=0, totalLoadTime=0, evictionCount=0}
10
10
CacheStats{hitCount=1, missCount=1, loadSuccessCount=1, loadExceptionCount=0, totalLoadTime=502324777, evictionCount=0}
10
10
10
CacheStats{hitCount=4, missCount=1, loadSuccessCount=1, loadExceptionCount=0, totalLoadTime=502324777, evictionCount=0}
10
10
CacheStats{hitCount=6, missCount=1, loadSuccessCount=1, loadExceptionCount=0, totalLoadTime=502324777, evictionCount=1}
10
10
10
CacheStats{hitCount=8, missCount=2, loadSuccessCount=2, loadExceptionCount=0, totalLoadTime=1002802169, evictionCount=1}

3. Caffeine cache  【Caffeine 本地缓存】

Caffeine cache is an optimized cache for Java 8. It has similar apis to guava but provide higher performance, which makes it easy to migrate from Gauva to Caffeine.

See this report for more details https://github.com/ben-manes/caffeine/wiki/Benchmarks

咖啡因缓存是专为Java 8而生的。使用上和Guava很像(很容易迁移),但它在多线程情况下性能更高。上面有一个跑分链接,比较了各种本地缓存的性能。

public class CaffeineCacheExample {
    static Cache<Integer, Integer> cache = Caffeine.newBuilder()
            .expireAfterWrite(2, TimeUnit.SECONDS)
            .recordStats()
            .build();

    static LoadingCache<Integer, Integer> loadingCache = Caffeine.newBuilder()
            .expireAfterWrite(2, TimeUnit.SECONDS)
            .build(new CacheLoader<Integer, Integer>() {
                @Override
                public Integer load(Integer key) throws Exception {
                    System.out.println("populate cache");
                    return key * 10;
                }
            });

    static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) throws Exception {
        useNormalCache();
    }

    static void useNormalCache() throws Exception {
        scheduler.scheduleWithFixedDelay(() -> System.out.println(cache.stats()), 0, 1, TimeUnit.SECONDS);
        for (int i = 0; i < 10; i++) {
            System.out.println(cache.get(0, k -> {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    //ignore
                }
                return 10;
            }));
            Thread.sleep(300);
        }
    }

    static void useLoadingCache() throws Exception {
        for (int i = 0; i < 10; i++) {
            System.out.println(loadingCache.get(1));
            Thread.sleep(300);
        }
    }
}

There exists slight difference between Guava and Caffeine

使用上,有一点小小的区别

1) Builder: Guava use CacheBuilder to create new builder while Caffeine use Caffeine.

创建Builder时,Guava使用CacheBuilder,咖啡因使用Caffeine

2) Get method: Guava pass callable for get method

两者的Get方法第二个参数略有区别Guava 传入Callable, 内部可以抛出异常,无需写冗余的try catch,而咖啡因传入Function,必须手动捕获可能的异常

V get(K var1, Callable<? extends V> var2) throws ExecutionException;

Caffeine pass Function for get method

 @CheckForNull
    V get(@Nonnull K var1, @Nonnull Function<? super K, ? extends V> var2);

Callable itself throws exception so we don't have to try catch the exception in the block while Function tolerates no exception.

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

A comparison of local caches (1) 【本地缓存之比较 (1)】的更多相关文章

  1. A comparison of local caches (2) 【本地缓存之比较 (2)】

    接上一篇: A comparison of local caches (1) [本地缓存之比较 (1)] This article will compare the asynchronous loca ...

  2. 八、React实战:可交互待办事务表(表单使用、数据的本地缓存local srtorage、生命同期函数(页面加载就会执行函数名固定为componentDidMount()))

    一.项目功能概述 示例网址:http://www.todolist.cn/ 功能: 输入待做事项,回车,把任务添加到 [正在进行] [正在进行] 任务,勾选之后,变成已[经完成事项] [已完成事务], ...

  3. spring boot: 用redis的消息订阅功能更新应用内的caffeine本地缓存(spring boot 2.3.2)

    一,为什么要更新caffeine缓存? 1,caffeine缓存的优点和缺点 生产环境中,caffeine缓存是我们在应用中使用的本地缓存, 它的优势在于存在于应用内,访问速度最快,通常都不到1ms就 ...

  4. spring boot:使用spring cache+caffeine做进程内缓存(本地缓存)(spring boot 2.3.1)

    一,为什么要使用caffeine做本地缓存? 1,spring boot默认集成的进程内缓存在1.x时代是guava cache 在2.x时代更新成了caffeine, 功能上差别不大,但后者在性能上 ...

  5. Java8简单的本地缓存实现

    原文出处:lukaseder         Java8简单的本地缓存实现 这里我将会给大家演示用ConcurrentHashMap类和lambda表达式实现一个本地缓存.因为Map有一个新的方法,在 ...

  6. iOS五种本地缓存数据方式

    iOS五种本地缓存数据方式   iOS本地缓存数据方式有五种:前言 1.直接写文件方式:可以存储的对象有NSString.NSArray.NSDictionary.NSData.NSNumber,数据 ...

  7. ImageLoader(多线程网络图片加载)+本地缓存 for windowsphone 7

    搞了好长一阵子wp,做点好事. C/S手机app中应用最多的是  获取网络图片,缓存到本地,展示图片 本次主要对其中的delay:LowProfileImageLoader进行修改,在获取图片的时候, ...

  8. lua模块demo(redis,http,mysql,cjson,本地缓存)

    1. lua模块demo(redis,http,mysql,cjson,本地缓存) 1.1. 配置 在nginx.conf中设置lua_shared_dict my_cache 128m; 开启ngi ...

  9. ASP.NET MVC深入浅出(被替换) 第一节: 结合EF的本地缓存属性来介绍【EF增删改操作】的几种形式 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery ) 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法 第六节: EF高级属性(二) 之延迟加载、立即加载、显示加载(含导航属性) 第十节: EF的三种追踪

    ASP.NET MVC深入浅出(被替换)   一. 谈情怀-ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态 ...

随机推荐

  1. MySQL最常用数值函数

    数值函数: 用来处理很多数值方面的运算,使用数值函数,可以免去很多繁杂的判断求值的过程,能够大大提高用户的工作效率. 1.ABS(x):返回 x 的绝对值 mysql> select abs(- ...

  2. javaWeb项目(SSH框架+AJAX+百度地图API+Oracle数据库+MyEclipse+Tomcat)之二 基础Hibernate框架搭建篇

    我们在搭建完Struts框架之后,从前台想后端传送数据就显得非常简单了.Struts的功能不仅仅是一个拦截器,这只是它的核心功能,此外我们也可以自定义拦截器,和通过注解的方式来更加的简化代码. 接下来 ...

  3. Vmware Vsphere WebService之vijava 开发一-vcenter连接、及集群信息获取

    开始是通过java代码调用vsphere提供的原始接口,从而控制vcenter的操作.当第一个版本做完之后发现代码执行的速度特别慢,后来在网上看到有人用vijava(对vsphere原始接口封装)编程 ...

  4. Linux centos7下安装配置redis及Redis desktop Manager工具连接注意事项

    基本工具:VMware12.CentOS-7-x86_64-Everything-1611.iso.redis-desktop-manager-0.8.0.3841 废话不多说,首先,关于什么是Red ...

  5. linux网络设置和虚拟机克隆转移之后Error:No suitable device found:no device found for connection 'System eth0'问题解决

    以root用户登录 #vi  /etc/sysconfig/network-scripts/ifcfg-eth0     #编辑配置文件,添加修改以下内容 BOOTPROTO=static   #启用 ...

  6. 【iOS开发】3.UIViewController

    1.概述 iOS和相关库的开发大量使用了模型-视图-控制器(MVC)模式.一般而言,MVC是一种策略,用于分离展现(视图).数据(模型)和业务逻辑(控制器).确切地讲,模型是简单数据,如Person或 ...

  7. Python之返回函数

    高阶函数可以把函数作为一个结果值返回 举例说明 普通的求积函数是 vim day5-6.py #!/usr/bin/python # -*- coding:utf-8 -*- def product( ...

  8. redis中键的生存时间(expire)

    1.redis中可以使用expire命令设置一个键的生存时间,到时间后redis会自动删除它 expire 设置生存时间(单位/秒) pexpire 设置生存时间(单位/毫秒) ttl/pttl 查看 ...

  9. jQuery遍历节点方法汇总

    1.children()方法:$('div').children()---遍历查找div元素的所有子元素节点 <p>Hello</p> <div> <span ...

  10. 记录——时间轮定时器(lua 实现)

    很长一段时间里,我错误的认识了定时器.无意中,我发现了“时间轮”这个名词,让我对定时器有了新的看法. 我错误的认为,定时器只需要一个 tick 队列,按指定的时间周期遍历队列,检查 tick 倒计时满 ...