Caffine
官方介绍Caffeine是基于JDK8的高性能本地缓存库,提供了几乎完美的命中率。它有点类似JDK中的ConcurrentMap,实际上,Caffeine中的LocalCache接口就是实现了JDK中的ConcurrentMap接口,但两者并不完全一样。最根本的区别就是,ConcurrentMap保存所有添加的元素,除非显示删除之(比如调用remove方法)。而本地缓存一般会配置自动剔除策略,为了保护应用程序,限制内存占用情况,防止内存溢出。
public class MyCaffine {
public static final Cache<String, Object> mycache;
static {
mycache = Caffeine.newBuilder()
// .expireAfterWrite(5000, TimeUnit.MINUTES) // 设置缓存过期时间为5分钟
.maximumSize(100) // 设置最大缓存条目数
.build();
}
}
@Scheduled 由Spring定义,用于将方法设置为调度任务。如:方法每隔十秒钟被执行、方法在固定时间点被执行等
-
@Scheduled(fixedDelay = 1000)
上一个任务结束到下一个任务开始的时间间隔为固定的1秒,任务的执行总是要先等到上一个任务的执行结束 -
@Scheduled(fixedRate = 1000)
每间隔1秒钟就会执行任务(如果任务执行的时间超过1秒,则下一个任务在上一个任务结束之后立即执行) -
@Scheduled(fixedDelay = 1000, initialDelay = 2000)
第一次执行的任务将会延迟2秒钟后才会启动 -
@Scheduled(cron = “0 15 10 15 * ?”)
Cron表达式,每个月的15号上午10点15分开始执行任务
@Component
public class MyScheduledTask {
@Resource
private ICommandService commandService;
// 每隔5秒执行一次定时任务
@Scheduled(fixedRate = 10000)
public void myTask() throws InterruptedException {
// 在此处定义您的定时任务逻辑
//继电器查询
String s = "0101000000083DCC";
List<Register> select = commandService.registerSelect(s);
MyCaffine.mycache.put("register", select);
Thread.sleep(2000);
//烟雾传感器的命令
String s1 = "03030003000175E8";
List<Smoke> smokes = commandService.smokeSelect(s1);
MyCaffine.mycache.put("smoke", smokes);
}
}
启动定时任务是需要的config中添加扫描包,这里我直接放在启动类中
@SpringBootApplication
@MapperScan("com.rui.online.mapper")
@EnableScheduling
public class OnlineApplication {
public static void main(String[] args) {
SpringApplication.run(OnlineApplication.class, args);
System.out.println("运行成功。。。。。。。。。。。。。。。。。。。。。。");
}
}
然后定时任务就完成了,我只需要在service或者control中调用这个caffine本地缓存库就行了
@GetMapping("/register/select")
public Response registerSelect() {
// String s = "0101000000083DCC";
// List<Register> select = commandService.registerSelect(s);
List<Register> register = (List<Register>) MyCaffine.mycache.getIfPresent("register");
return Response.ok("成功", register);
}
@GetMapping("/smoke/select")
public Response smokeSelect() {
// String s = "03030003000175E8";
// List<Smoke> smokes = commandService.smokeSelect(s);
// List<Smoke>
List<Smoke> smoke = (List<Smoke>) MyCaffine.mycache.getIfPresent("smoke");
return Response.ok("成功", smoke);
}
查看日志,每隔10秒就行进行一次日志输出