是否正确使用了 CacheLoader?

Is it proper use of CacheLoader?

请问在缓存中没有key的情况下load方法怎么办? 我通过 put 方法手动将元素添加到缓存中:

@Override
    public void addResources(....) {
                    SomeId someId = SomeId.builder()
                            ....
                            .build();
                    cache.put(someId, r.getResource());
    }

之后我在 LoadingCache 中寻找那个密钥。如果它包含密钥,我将通过 get 方法获取它。

@Override

  public InputStream someMethod(String uri) throws ExecutionException {
        SomeId someId = SomeId.builder()
                ...
                .build();
        if ( cache.asMap()
                .containsKey(someId) ) {
            return new ByteArrayInputStream(cache.get(someId));
        } else {
            ....
            }
            return is;
        }
    }

我这样初始化这个缓存:

 private static LoadingCache<SomeId, byte[]> cache;

    @PostConstruct
    public void init() {
        cache = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(24, TimeUnit.HOURS)
                .build(new CacheLoader<SomeId, byte[]>() {
                    @Override
                    public byte[] load(SomeId someId) {
                        throw new IllegalStateException("");
                    }
                });
    }

我现在知道我应该在里面做什么了:

@Override
                        public byte[] load(SomeId someId) {
throw new IllegalStateException("");
                        }

因为我不只是从这个缓存中加载任何数据库中的元素。如果元素不在缓存中,我什么都不应该做。值得注意的是,如果缓存中存在密钥,我正在检查方法

 if ( cache.asMap()
                .containsKey(someId) ) {
            return new ByteArrayInputStream(cache.get(someId));

您并不是真的需要 LoadingCache,纯 Cache 就足以满足您的用例。只是不要将任何东西传递给 .build(),你应该可以开始了:

private static Cache<SomeId, byte[]> cache;

// ... init
    cache = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(24, TimeUnit.HOURS)
            .build();

用法:

byte[] value = cache.getIfPresent(someId);
if (value != null) { // if key is not present, null is returned
    return new ByteArrayInputStream(value);
} else {
    // ...
}