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

avatar
作者
筋斗云
阅读量:0

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

```java

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 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`来创建本地缓存,需要在项目中引入相应的依赖。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!