Java Cache Expiration: Set Time Limits

In Java, you can create a local cache and set expiration time using the CacheBuilder class. Below is an example code:

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.TimeUnit;

public class LocalCacheExample {

    public static void main(String[] args) {
        // 创建一个本地缓存,设置最大缓存大小为100,过期时间为10分钟
        Cache<String, String> cache = CacheBuilder.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .build();

        // 将键值对放入缓存中
        cache.put("key1", "value1");
        cache.put("key2", "value2");

        // 从缓存中获取值
        String value1 = cache.getIfPresent("key1");
        String value2 = cache.getIfPresent("key2");

        System.out.println("value1: " + value1);
        System.out.println("value2: " + value2);

        // 休眠11分钟,此时缓存中的数据应该已经过期
        try {
            Thread.sleep(11 * 60 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 再次尝试获取缓存中的值
        value1 = cache.getIfPresent("key1");
        value2 = cache.getIfPresent("key2");

        System.out.println("value1 after expiration: " + value1);
        System.out.println("value2 after expiration: " + value2);
    }
}

In the code above, a cache builder is created using CacheBuilder.newBuilder(), then the maximum size of the cache is set by calling the maximumSize() method and the expiration time of the cache data is set using the expireAfterWrite() method. Finally, the cache object is built by calling the build() method.

It is important to note that the examples above use CacheBuilder from the Guava library to create local caches, the corresponding dependencies need to be included in the project.

bannerAds