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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7864637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:45:35  来源:igfitidea点击:

What is the best way to cache single object within fixed timeout?

javaguava

提问by Alexey Zakharov

Google Guava has CacheBuilder that allows to create ConcurrentHash with expiring keys that allow to remove entries after the fixed tiemout. However I need to cache only one instance of certain type.

Google Guava 有 CacheBuilder,它允许创建带有过期键的 ConcurrentHash,允许在固定超时后删除条目。但是我只需要缓存某种类型的一个实例。

What is the best way to cache single object within fixed timeout using Google Guava?

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

回答by Etienne Neveu

I'd use Guava's Suppliers.memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit)

我会使用 Guava 的Suppliers.memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit)

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

Update with JDK 8

使用 JDK 8 更新

Today, I would write this code differently, using JDK 8 method references and constructor injection for cleaner code:

今天,我将以不同的方式编写此代码,使用 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();
    }
}