【guava】GuavaCache缓存失效的时候做一些操作 RemovalListener

在这里插入图片描述

1.概述

转载:https://blog.csdn.net/chen_kkw/article/details/81144169

缓存策略参考:【Guava】Guava Cache的refresh和expire刷新机制

以为需要我使用guava缓存我的数据库连接,但是因为设置了1分钟失效就关闭,但是关闭的时候,我希望能做些操作,最好是关闭连接,代码如下

private static class MyRemovalListener implements RemovalListener<Integer, Integer> {
    
      
    @Override  
    public void onRemoval(RemovalNotification<Integer, Integer> notification) {
    
      
        doSomething();
    }  
}  

public static Cache<Integer, Integer> cache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(new MyRemovalListener())
.build();

看上去应该没什么问题,只是测试下来发现回调并不触发,如果手动调用 invalidate(key) 的话,那么就会触发回调,但是这不符合我的需求啊,我是希望 key 在 10 min 过期之后能自己触发回调,而且这 API 既然设计成这样,没道理不能触发,于是开始寻找问题

2.原因

在 Stack Overflow 上找到了原因,原来是 GuavaCache 并不保证在过期时间到了之后立刻删除该 Key,如果你此时去访问了这个 Key,它会检测是不是已经过期,过期就删除它,所以过期时间到了之后你去访问这个 Key 会显示这个 Key 已经被删除,但是如果你不做任何操作,那么在 10 min 到了之后也许这个 Key 还在内存中。GuavaCache 选择这样做的原因也很简单,如下:

The reason for this is as follows: if we wanted to perform Cache maintenance continuously, we would need to create a thread, and its operations would be competing with user operations for shared locks. Additionally, some environments restrict the creation of threads, which would make CacheBuilder unusable in that environment.

这样做既可以保证对 Key 读写的正确性,也可以节省资源,减少竞争。

参考:https://blog.csdn.net/chen_kkw/article/details/81144169

猜你喜欢

转载自blog.csdn.net/qq_21383435/article/details/108835568