Java项目启动时先加载某些方法可用于redis缓存预热
业务场景:在系统启动后需要先加载某些方法,例如加载热点数据到redis进行缓存预热
importlombok.extern.slf4j.Slf4j;
importorg.springframework.stereotype.Service;
importjavax.annotation.PostConstruct;
@Slf4j
@Service
publicclassFirstService {
@PostConstruct
publicvoidtest() {
System.out.println("First-PostConstruct:开始运行...");
}
}
importlombok.extern.slf4j.Slf4j;
importorg.springframework.boot.CommandLineRunner;
importorg.springframework.stereotype.Service;
importjavax.annotation.PostConstruct;
@Slf4j
@Service
publicclassTwoServiceimplementsCommandLineRunner {
@Override
publicvoidrun(String... args) throwsException {
System.out.println("Two-CommandLineRunner:开始运行...");
}
}
importlombok.extern.slf4j.Slf4j;
importorg.springframework.boot.ApplicationArguments;
importorg.springframework.boot.ApplicationRunner;
importorg.springframework.boot.CommandLineRunner;
importorg.springframework.stereotype.Service;
@Slf4j
@Service
publicclassThreeServiceimplementsApplicationRunner {
@Override
publicvoidrun(ApplicationArgumentsargs) throwsException {
System.out.println("Three-ApplicationRunner:开始运行...");
}
}
执行顺序 @PostConstruct
—>ApplicationRunner
—>CommandLineRunner
缓存预热
1、定义
缓存预热就是在系统上线后,先加载某些热点key,防止出现缓存击穿
2、解决方案
1)手动写一个加载热点key的方法,上线后调用一下2)数据量不大,可以在项目启动的时候自动进行加载。3)通过定时任务刷新缓存。