GUAVA缓存失效清理

【GUAVA缓存失效清理】GUAVA缓存虽然有expireAfterWrite/expireAfterAccess方法和expire的监听器,但是guava自身并不会定时去判断缓存是否失效,触发判断失效逻辑是调用get方法。这自然很难满足需要对失效缓存进行监控的场景。解决方案如下:

@ConditionalOnProperty(value = "https://www.it610.com/article/spring.application.heartBeatWeb", havingValue = "https://www.it610.com/article/1") @Component public class HeartBeatInitializer extends BaseController implements ApplicationRunner {private static final Logger LOG = LoggerFactory.getLogger(HeartBeatInitializer.class); @Value("${spring.application.heartBeatWeb}") private int heartBeatWeb; @Resource private HeartBeatConfig heartBeatConfig; @Resource private HeartBeatServiceImpl heartBeatService; @Resource private IRedisService redisService; @Resource private KafkaTemplate kafkaTemplate; @Resource private ThreadPoolTaskScheduler threadPoolTaskScheduler; @Override public void run(ApplicationArguments applicationArguments) throws Exception {try { Thread.sleep(2000); heartBeatService.setHeartBeatCache(CacheBuilder.newBuilder().expireAfterAccess(baseResponse.getData().getStopRequestTime(), TimeUnit.SECONDS).removalListener(new RemovalListener() { @Override public void onRemoval(RemovalNotification removalNotification) { LOG.info("被移除了:" + removalNotification.getCause()); } }).build()); threadPoolTaskScheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { schedule(); } catch (ExecutionException e) { e.printStackTrace(); } } },baseResponse.getData().getStopRequestTime()*500); } } catch (Exception e) { LOG.error(e.getMessage(), e); }}public void schedule() throws ExecutionException { LOG.info("定时器"); heartBeatService.getHeartBeatCache().cleanUp(); } }

    推荐阅读