SpringBoot實(shí)現(xiàn)數(shù)據(jù)預(yù)熱的方式小結(jié)
Springboot如何實(shí)現(xiàn)數(shù)據(jù)預(yù)熱
這里用到的數(shù)據(jù)預(yù)熱,就是在項(xiàng)目啟動時將一些數(shù)據(jù)量較大的數(shù)據(jù)加載到緩存中(筆者這里用的Redis)。那么在項(xiàng)目啟動有哪些方式可以實(shí)現(xiàn)數(shù)據(jù)預(yù)熱呢?
1、方式一:ApplicationRunner接口
package org.springframework.boot;
@FunctionalInterface
public interface ApplicationRunner {
/**
* 用于運(yùn)行Bean的回調(diào)。
* @param 參數(shù)傳入的應(yīng)用程序參數(shù)
* @throws 出錯時出現(xiàn)異常
*/
void run(ApplicationArguments args) throws Exception;
}ApplicationRunner接口的run方法:
void run(ApplicationArguments args) throws Exception;
1、ApplicationRunner在所有的ApplicationContext上下文都刷新和加載完成后(Spring Bean已經(jīng)被完全初始化)被調(diào)用,在ApplicationRunner的run方法執(zhí)行之前,所有。
2、在ApplicationRunner中,可以直接通過 ApplicationArguments對象來獲取命令行參數(shù)和選項(xiàng)。
實(shí)現(xiàn)接口
@Component
public class DataPreloader implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(DataPreloader.class);
@Override
public void run(ApplicationArguments args) {
log.info("數(shù)據(jù)預(yù)熱啟動, 這里會在系統(tǒng)啟動后執(zhí)行"));
}
}2、方式二:CommandLineRunner接口
package org.springframework.boot;
@FunctionalInterface
public interface CommandLineRunner {
/**
* 用于運(yùn)行Bean的回調(diào)。
* @param Args傳入的Main方法參數(shù)
* @throws 出錯時出現(xiàn)異常
*/
void run(String... args) throws Exception;
}CommandLineRunner接口的run方法:
void run(String... args) throws Exception;
1、在CommandLineRunner中,命令行參數(shù)將以字符串?dāng)?shù)組的形式傳遞給
run方法。
實(shí)現(xiàn)接口
@Component
public class DataPreloader2 implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(DataPreloader2.class);
@Override
public void run(String... args){
log.info("數(shù)據(jù)預(yù)熱啟動, 這里會在系統(tǒng)啟動后執(zhí)行");
}
}3、區(qū)別
- CommandLineRunner在ApplicationRunner之后被調(diào)用,也是在所有的ApplicationContext上下文都刷新和加載完成后執(zhí)行。但是,與ApplicationRunner不同的是,CommandLineRunner#run方法執(zhí)行之前,SpringApplication#run方法的參數(shù)也會被作為命令行參數(shù)傳遞給run方法。
- 如果需要訪問命令行參數(shù)和選項(xiàng),或者需要在所有Bean初始化之前執(zhí)行特定的操作,你可以選擇使用ApplicationRunner。如果你只需要在所有Bean初始化之后執(zhí)行某些操作,你可以使用CommandLineRunner。
無論你選擇使用ApplicationRunne還是CommandLineRunner,它們都提供了在Spring Boot項(xiàng)目啟動時執(zhí)行自定義邏輯的能力。你可以根據(jù)實(shí)際需求選擇適合的接口來實(shí)現(xiàn)項(xiàng)目預(yù)熱或其他操作。
以上就是SpringBoot實(shí)現(xiàn)數(shù)據(jù)預(yù)熱的方式小結(jié)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot數(shù)據(jù)預(yù)熱的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring Cloud Zuul路由網(wǎng)關(guān)服務(wù)過濾實(shí)現(xiàn)代碼
這篇文章主要介紹了Spring Cloud Zuul路由網(wǎng)關(guān)服務(wù)過濾實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
SpringBoot文件上傳大小設(shè)置方式(yml中配置)
這篇文章主要介紹了SpringBoot文件上傳大小設(shè)置方式(yml中配置),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Spring Security OAuth2集成短信驗(yàn)證碼登錄以及第三方登錄
這篇文章主要介紹了Spring Security OAuth2集成短信驗(yàn)證碼登錄以及第三方登錄,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04

