小编典典

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

java

Google
Guava具有CacheBuilder,它允许使用到期密钥创建ConcurrentHash,从而允许在固定的平局之后删除条目。但是,我只需要缓存一个特定类型的实例。

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


阅读 253

收藏
2020-12-03

共1个答案

小编典典

我会用番石榴的Suppliers.memoizeWithExpiration(供应商委托,持续时间长,TimeUnit单位)

public class JdkVersionService {

    @Inject
    private JdkVersionWebService jdkVersionWebService;

    // No need to check too often. Once a year will be good :) 
    private final Supplier<JdkVersion> latestJdkVersionCache
            = Suppliers.memoizeWithExpiration(jdkVersionSupplier(), 365, TimeUnit.DAYS);


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

    private Supplier<JdkVersion> jdkVersionSupplier() {
        return new Supplier<JdkVersion>() {
            public JdkVersion get() {
                return jdkVersionWebService.checkLatestJdkVersion();
            }
        };
    }
}

用JDK 8更新

今天,我将使用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();
    }
}
2020-12-03