Home  >  Article  >  Java  >  How to set expiration time map in Java

How to set expiration time map in Java

WBOY
WBOYforward
2023-05-04 10:13:063003browse

1. Technical background

In actual project development, we often use caching middleware (such as redis, MemCache, etc.) to help us improve the availability and robustness of the system.

But many times if the project is relatively simple, there is no need to specifically introduce middleware such as Redis to use cache to increase the complexity of the system. So does Java itself have any useful lightweight caching components?

The answer is of course yes, and there is more than one way. Common solutions include: ExpiringMap, LoadingCache and HashMap-based packaging.

2. Technical effect

  • Realize common functions of cache, such as outdated deletion strategy

  • Hot data warm-up

3. ExpiringMap

3.1 Function Introduction

  • Entries in the Map can be set to automatically expire after a period of time.

  • You can set the maximum capacity value of the Map. When the Maximum size is reached, inserting a value again will cause the first value in the Map to expire.

  • You can add listening events and schedule the listening function when the Entry expires.

  • You can set up lazy loading and create objects when the get() method is called.

3.2 Source code

github address

3.3 Example

Add dependency (Maven)

<dependency> 
    <groupId>net.jodah</groupId> 
    <artifactId>expiringmap</artifactId> 
    <version>0.5.8</version> 
</dependency>

Example source code

public class ExpiringMapApp {

    public static void main(String[] args) {
        // maxSize: 设置最大值,添加第11个entry时,会导致第1个立马过期(即使没到过期时间)
        // expiration:设置每个key有效时间10s, 如果key不设置过期时间,key永久有效。
        // variableExpiration: 允许更新过期时间值,如果不设置variableExpiration,不允许后面更改过期时间,一旦执行更改过期时间操作会抛异常UnsupportedOperationException
        // policy:
        //        CREATED: 只在put和replace方法清零过期时间
        //        ACCESSED: 在CREATED策略基础上增加, 在还没过期时get方法清零过期时间。
        //        清零过期时间也就是重置过期时间,重新计算过期时间.
        ExpiringMap<String, String> map = ExpiringMap.builder()
            .maxSize(10)
            .expiration(10, TimeUnit.SECONDS)
            .variableExpiration().expirationPolicy(ExpirationPolicy.CREATED).build();

        map.put("token", "lkj2412lj1412412nmlkjl2n34l23n4");
        map.put("name", "管理员", 20000, TimeUnit.SECONDS);

        // 模拟线程等待...
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("token ===> " + map.get("token"));
        System.out.println("name ===> " + map.get("name"));

        // 注意: 在创建map时,指定的那些参数如过期时间和过期策略都是全局的, 对map中添加的每一个entry都适用.
        //        在put一个entry键值对时可以对当前entry 单独设置 过期时间、过期策略,只对当前这个entry有效.
    }
}

Run result

##token ===> null

name ===> Administrator

Attention

When creating a map, the specified parameters such as expiration time and expiration policy are global and apply to every entry added to the map.
When putting an entry key-value pair, you can set the expiration time and expiration policy separately for the current entry, which is only valid for the current entry.

4. LoadingCache

4.1 Function Introduction

A thread-safe local caching solution open sourced by Google.

Features: Provide cache recycling mechanism, monitor cache loading/hit status, flexible and powerful functions, simple and easy-to-use API.

4.2 Example

Source code

public class LoadingCacheApp {

    public static void main(String[] args) throws Exception {
        // maximumSize: 缓存池大小,在缓存项接近该大小时, Guava开始回收旧的缓存项
        // expireAfterAccess: 设置时间对象没有被读/写访问则对象从内存中删除(在另外的线程里面不定期维护)
        // removalListener: 移除监听器,缓存项被移除时会触发的钩子
        // recordStats: 开启Guava Cache的统计功能
        LoadingCache<String, String> cache = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterAccess(10, TimeUnit.SECONDS)
            .removalListener(new RemovalListener<String, String>() {
                @Override
                public void onRemoval(RemovalNotification<String, String> removalNotification) {
                    System.out.println("过时删除的钩子触发了... key ===> " + removalNotification.getKey());
                }
            })
            .recordStats()
            .build(new CacheLoader<String, String>() {
                // 处理缓存键不存在缓存值时的处理逻辑
                @Override
                public String load(String key) throws Exception {
                    return "不存在的key";
                }
            });

        cache.put("name", "小明");
        cache.put("pwd", "112345");

        // 模拟线程等待...
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("token ===> " + cache.get("name"));
        System.out.println("name ===> " + cache.get("pwd"));
    }
}

Run result

The outdated deletion hook triggered... key ===> name

token ===> Non-existent key
The obsolete deletion hook triggered... key ===> pwd
name ===> Non-existent key

4.3 Removal mechanism

When guava caches data, there are two types of data removal: passive removal and active removal.

Passive removal

  • Size-based removal: When the number reaches the specified size, uncommon key values ​​will be removed

  • Time-based removal: expireAfterAccess(long, TimeUnit) removes a key-value pair based on the time after the last access. expireAfterWrite(long, TimeUnit) Remove based on the time after a key-value pair is created or the value is replaced

  • Reference-based removal: mainly based on Java's garbage collection mechanism. Determine removal based on the reference relationship of the key or value

Active removal

  • Remove individually: Cache.invalidate(key)

  • Batch removal: Cache.invalidateAll(keys)

  • Remove all: Cache.invalidateAll()

If the removal listener RemovalListener is configured, the logic under the listener will be executed synchronously during all removal actions.

If you need to change to asynchronous, use: RemovalListeners.asynchronous(RemovalListener, Executor).

4.4 Others

  • Before the put operation, if it has With this key value, removeListener will be triggered first to remove the listener, and then

  • is configured with expireAfterAccess and expireAfterWrite, but it is not removed after the specified time.

  • Delete policy logic:

The cache built by CacheBuilder will not automatically perform cleaning and recycling work at a specific time, nor will it be executed at a certain time. The cache item is cleared immediately after it expires. It does not start a thread for cache maintenance, because firstly the thread is relatively heavy, and secondly some environments limit the creation of threads.

It will do a small amount of maintenance work during write operations, or occasionally during read operations. Of course, you can also create your own maintenance thread and call Cache.cleanUp() at fixed intervals.

The above is the detailed content of How to set expiration time map in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete