【问题标题】:Is it proper use of CacheLoader?是否正确使用 CacheLoader?
【发布时间】:2021-10-30 21:03:26
【问题描述】:

想问一下当缓存中不包含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));

【问题讨论】:

    标签: java caching guava


    【解决方案1】:

    你真的不需要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 {
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 1970-01-01
      • 2016-01-24
      • 2014-05-15
      • 2010-12-31
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多