本文主要是介绍GUAVA缓存失效清理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
GUAVA缓存虽然有expireAfterWrite/expireAfterAccess方法和expire的监听器,但是guava自身并不会定时去判断缓存是否失效,触发判断失效逻辑是调用get方法。这自然很难满足需要对失效缓存进行监控的场景。解决方案如下:
@ConditionalOnProperty(value = "spring.application.heartBeatWeb", havingValue = "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;@Resourceprivate HeartBeatConfig heartBeatConfig;@Resourceprivate HeartBeatServiceImpl heartBeatService;@Resourceprivate IRedisService redisService;@Resourceprivate KafkaTemplate kafkaTemplate;@Resourceprivate ThreadPoolTaskScheduler threadPoolTaskScheduler;@Overridepublic void run(ApplicationArguments applicationArguments) throws Exception {try {Thread.sleep(2000);heartBeatService.setHeartBeatCache(CacheBuilder.newBuilder().expireAfterAccess(baseResponse.getData().getStopRequestTime(), TimeUnit.SECONDS).removalListener(new RemovalListener<String, Object>() {@Overridepublic void onRemoval(RemovalNotification<String, Object> removalNotification) {LOG.info("被移除了:" + removalNotification.getCause());}}).build());threadPoolTaskScheduler.scheduleAtFixedRate(new Runnable() {@Overridepublic 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();}
}
这篇关于GUAVA缓存失效清理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!