Java 项目启动时先加载某些方法可用于 redis 缓存预热
业务场景:在系统启动后需要先加载某些方法,例如加载热点数据到 redis 进行缓存预热
 import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Slf4j@Servicepublic class FirstService {
    @PostConstruct    public void test() {        System.out.println("First-PostConstruct:开始运行...");    }
}
import lombok.extern.slf4j.Slf4j;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Slf4j@Servicepublic class TwoService implements CommandLineRunner {    @Override    public void run(String... args) throws Exception {        System.out.println("Two-CommandLineRunner:开始运行...");    }}
import lombok.extern.slf4j.Slf4j;import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Service;
@Slf4j@Servicepublic class ThreeService implements ApplicationRunner {
    @Override    public void run(ApplicationArguments args) throws Exception {        System.out.println("Three-ApplicationRunner:开始运行...");    }}
       复制代码
 
执行顺序 @PostConstruct—>ApplicationRunner—>CommandLineRunner
缓存预热
1、定义
缓存预热就是在系统上线后,先加载某些热点 key,防止出现缓存击穿
2、解决方案
1)手动写一个加载热点 key 的方法,上线后调用一下 2)数据量不大,可以在项目启动的时候自动进行加载。3)通过定时任务刷新缓存。
评论