温馨提示×

java本地缓存怎么设置过期时间

小亿
258
2024-02-29 13:53:29
栏目: 编程语言

在Java中,可以通过使用CacheBuilder类来创建本地缓存并设置过期时间。以下是一个示例代码:

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

在上面的代码中,使用CacheBuilder.newBuilder()来创建一个缓存构建器,然后通过调用maximumSize()方法设置缓存的最大大小,expireAfterWrite()方法设置缓存数据的过期时间。最后通过调用build()方法来构建缓存对象。

需要注意的是,以上示例中使用了Guava库中的CacheBuilder来创建本地缓存,需要在项目中引入相应的依赖。

0