Google’s local cache is really easy to use

In normal development, we often use dictionaries. For example, we store the device code in our database, and display the device name; what is stored in the database is the user id and the user name is displayed. We will frequently call such fields, and then we will frequently query the database. In order to ensure the access speed, we will use the cache. But if you use middleware caching like Redis, it's a little overkill. Of course, we can also store the required data in the Map by ourselves, but we must consider the estimated capacity of the Map, the time of data caching, and so on. So the design of the Map is more troublesome.

Here I recommend the local cache in Guava, Google's library framework.

Before using, we first quote Guava's Maven dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

Let's first write an entity class for the provincial capital Province:

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Province {
    //省会名称
    private String name;
    //省会编码 如:PR001
    private String code;
}

Two fields are defined here, the name of the provincial capital and the code of the provincial capital. Generally, the code is stored in the inventory code. When displaying, we need to query and obtain it in a special table name.

Let's define a listener for cache invalidation CustomizeRemovalListener:

public class CustomizeRemovalListener implements RemovalListener<String, Province> {
    @Override
    public void onRemoval(RemovalNotification<String, Province> removalNotification) {
        String reason = String.format("key=%s,value=%s,reason=%s", removalNotification.getKey(), removalNotification.getValue(), removalNotification.getCause());
        System.out.println(reason);
    }
}

When we manually invalidate the cache, or the expiration time is up, it will be monitored. The console will print out reason. onRemoval()Methods can be written according to business needs.

Let's use the cache:

As in the above code, when we call the loadingCache.get()method , we will first look it up in the cache. If it is not in the cache, we will execute this code:

// 如果找不到元素,会调用这里
@Override
public Province load(String s) {
    //实际情况这里就是查库
    System.out.println("查了数据库哦");
    return getDataFromDb();
}

Let's check the library in this code. In the illustrated code, we first create an initial cache:

LoadingCache<String, Province> loadingCache = CacheBuilder.newBuilder()
        .maximumSize(1000) // 容量
        .expireAfterWrite(3, TimeUnit.SECONDS) // 过期时间
        .removalListener(new CustomizeRemovalListener()) // 失效监听器
        .build(cacheLoader);

Here, the initial capacity of the cache, expiration time, and monitoring functions after the cache expires are created.

We store the data in the cache:

loadingCache.put("PR001", getDataFromDb());

The first 3 fetches are all loadingCachefetching values from the cache . When the thread sleeps for 4 seconds and the expiration time is exceeded, the cache will be invalidated and the listener will be triggered. 4th'll get from load(String s)get in.

The console print results are as follows:

第一次获取:Province(name=北京, code=PR001)
第二次获取:Province(name=北京, code=PR001)
第三次获取:Province(name=北京, code=PR001)
key=PR001,value=Province(name=北京, code=PR001),reason=EXPIRED
查了数据库哦
第四次获取:Province(name=北京, code=PR001)

This code

key=PR001,value=Province(name=北京, code=PR001),reason=EXPIRED

The display cache expired due to timeout.

Of course, Guava still has many functions. If you are interested in children's shoes, please read this article I wrote:

[Programmer's Gospel-Guava] ( Programmer's Gospel-Guava (qq.com) )

Of course, there are many local cache frameworks in the world, such as Caffeine (an upgraded version of Guava cache), Ehcache, etc. Interested children's shoes can go and learn about it.

Recommended in the past

Scan the QR code to get more exciting. Or search Lvshen_9 on WeChat , you can reply to get information in the background

  1. 回复"java" 获取java电子书;

  2. 回复"python"获取python电子书;

  3. 回复"算法"获取算法电子书;

  4. 回复"大数据"获取大数据电子书;

  5. 回复"spring"获取SpringBoot的学习视频。

  6. 回复"面试"获取一线大厂面试资料

  7. 回复"进阶之路"获取Java进阶之路的思维导图

  8. 回复"手册"获取阿里巴巴Java开发手册(嵩山终极版)

  9. 回复"总结"获取Java后端面试经验总结PDF版

  10. 回复"Redis"获取Redis命令手册,和Redis专项面试习题(PDF)

  11. 回复"并发导图"获取Java并发编程思维导图(xmind终极版)

Another: Click [ My Benefits ] to have more surprises.

Guess you like

Origin blog.csdn.net/wujialv/article/details/111038267