代码拉取完成,页面将自动刷新
/**
* @return void
* @description worker验证间隔时间超过一分钟的热键的计算的准确性
* @params [args]
* @author wmh
* @date 2022/5/12 16:38
*/
public static void main(String[] args) {
/**
* 因CaffeineBuilder.buildAllKeyCache中设置的滑动窗口的缓存过期时间为一分钟(expireAfterWrite),
* 滑动窗口可设置的最大间隔时间为10分钟(maxDuration),
* 会造成超过1分钟间隔时间的热键的滑动窗口缓存丢失,从而造成统计有误
* 是否(expireAfterWrite,maxDuration)两者保持一致会比较好
*/
String key = "testKey";
final Cache<String, Object> cache = CaffeineCacheHolder.getCache(null);
SlidingWindow window = (SlidingWindow) cache.get(key, (Function<String, SlidingWindow>) k -> {
System.out.println("new cache");
KeyRule keyRule = new KeyRule(k, false, 65, 2, 10);
return new SlidingWindow(keyRule.getInterval(), keyRule.getThreshold());
});
System.out.println("start = " + window.addCount(1));
try {
Thread.sleep(62000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
//放开注释,因为持有滑动窗口对象,所以统计正确
// System.out.println("result = " + window.addCount(1));
//重新获取滑动窗口对象,会新创一个对象,丢失之前的数据
window = (SlidingWindow) cache.get(key, (Function<String, SlidingWindow>) k -> {
System.out.println("lost cache");
KeyRule keyRule = new KeyRule(k, false, 65, 2, 10);
return new SlidingWindow(keyRule.getInterval(), keyRule.getThreshold());
});
System.out.println("result = " + window.addCount(1));
//程序无法退出,是因为CaffeineBuilder中的线程池未停止,建议添加停止入口
//CaffeineBuilder.executorService.shutdown();