Java 在固定超时内缓存单个对象的最佳方式是什么?

Java 在固定超时内缓存单个对象的最佳方式是什么?,java,guava,Java,Guava,Google Guava有一个CacheBuilder,它允许创建带有过期密钥的ConcurrentHash,允许在修复tiemout后删除条目。但是,我只需要缓存一个特定类型的实例 使用Google Guava在固定超时内缓存单个对象的最佳方法是什么?我会使用Guava的 公共类JdkVersionService{ @注入 私有JdkVersionWebService JdkVersionWebService; //不需要经常检查。一年一次就好:) 私人最终供应商最新JDKVersionCac

Google Guava有一个CacheBuilder,它允许创建带有过期密钥的ConcurrentHash,允许在修复tiemout后删除条目。但是,我只需要缓存一个特定类型的实例

使用Google Guava在固定超时内缓存单个对象的最佳方法是什么?

我会使用Guava的

公共类JdkVersionService{
@注入
私有JdkVersionWebService JdkVersionWebService;
//不需要经常检查。一年一次就好:)
私人最终供应商最新JDKVersionCache
=Suppliers.MemorizeWitheExption(jdkVersionSupplier(),365,时间单位.DAYS);
公共JdkVersion getLatestJdkVersion(){
返回latestJdkVersionCache.get();
}
私人供应商jdkVersionSupplier(){
退回新供应商(){
公共JdkVersion get(){
返回jdkVersionWebService.checkLatestJdkVersion();
}
};
}
}
使用jdk8更新 今天,我将以不同的方式编写此代码,使用JDK 8方法引用和构造函数注入来实现更干净的代码:

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.google.common.base.Suppliers;

@Service
public class JdkVersionService {

    private final Supplier<JdkVersion> latestJdkVersionCache;

    @Inject
    public JdkVersionService(JdkVersionWebService jdkVersionWebService) {
        this.latestJdkVersionCache = Suppliers.memoizeWithExpiration(
                jdkVersionWebService::checkLatestJdkVersion,
                365, TimeUnit.DAYS
        );
    }

    public JdkVersion getLatestJdkVersion() {
        return latestJdkVersionCache.get();
    }
}
import java.util.concurrent.TimeUnit;
导入java.util.function.Supplier;
导入javax.inject.inject;
导入org.springframework.stereotype.Service;
导入com.google.common.base.Suppliers;
@服务
公共类JdkVersionService{
私人最终供应商最新JDKVersionCache;
@注入
公共JdkVersionService(JdkVersionWebService JdkVersionWebService){
this.latestJdkVersionCache=Suppliers.MemoizeWitheExption(
jdkVersionWebService::checkLatestJdkVersion,
365,时间单位。天
);
}
公共JdkVersion getLatestJdkVersion(){
返回latestJdkVersionCache.get();
}
}

您知道供应商抛出选中异常时的解决方案吗?@user2417480我可能会将该异常包装在RuntimeException中。如果你真的想保留一个已检查的异常,也许以后再打开它,但它通常是一种反模式,在多个层中携带一个已检查的异常。。。这就是为什么SpringJDBC有一个转换层将检查的异常转换为运行时DataAccessException。
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.google.common.base.Suppliers;

@Service
public class JdkVersionService {

    private final Supplier<JdkVersion> latestJdkVersionCache;

    @Inject
    public JdkVersionService(JdkVersionWebService jdkVersionWebService) {
        this.latestJdkVersionCache = Suppliers.memoizeWithExpiration(
                jdkVersionWebService::checkLatestJdkVersion,
                365, TimeUnit.DAYS
        );
    }

    public JdkVersion getLatestJdkVersion() {
        return latestJdkVersionCache.get();
    }
}