有直接拿来用的吗
时间: 2024-02-28 13:52:44 浏览: 11
有,Guava这个库中提供了一个CacheBuilder类,可以很方便地创建一个过期缓存。示例代码如下:
```
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class ExpiringCache<K, V> {
private final LoadingCache<K, V> cache;
public ExpiringCache(long expireDuration, TimeUnit timeUnit) {
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder()
.expireAfterWrite(expireDuration, timeUnit);
cache = builder.build(new CacheLoader<K, V>() {
@Override
public V load(K key) {
throw new RuntimeException("Not implemented");
}
});
}
public void put(K key, V value) {
cache.put(key, value);
}
public V get(K key) throws ExecutionException {
return cache.get(key);
}
public void clear() {
cache.invalidateAll();
}
public void shutdown() {
cache.cleanUp();
}
}
```
构造函数中的expireDuration和timeUnit表示缓存的过期时间,put方法用于向缓存中添加数据,get方法用于从缓存中获取数据,clear方法用于清空缓存,shutdown方法用于清理缓存中的所有数据。
使用方法如下:
```
ExpiringCache<String, Integer> cache = new ExpiringCache<>(5, TimeUnit.SECONDS);
cache.put("key1", 1);
cache.put("key2", 2);
System.out.println(cache.get("key1")); // 输出1
Thread.sleep(6000);
System.out.println(cache.get("key1")); // 输出null
```
这个实现比较简单,使用起来也比较方便。另外,Guava库中还提供了很多其他的缓存实现,可以根据具体需求选择合适的实现。