SpringBoot實現(xiàn)數(shù)據(jù)預熱的方式小結
Springboot如何實現(xiàn)數(shù)據(jù)預熱
這里用到的數(shù)據(jù)預熱,就是在項目啟動時將一些數(shù)據(jù)量較大的數(shù)據(jù)加載到緩存中(筆者這里用的Redis
)。那么在項目啟動有哪些方式可以實現(xiàn)數(shù)據(jù)預熱呢?
1、方式一:ApplicationRunner接口
package org.springframework.boot; @FunctionalInterface public interface ApplicationRunner { /** * 用于運行Bean的回調(diào)。 * @param 參數(shù)傳入的應用程序參數(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à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ù)預熱啟動, 這里會在系統(tǒng)啟動后執(zhí)行")); } }
2、方式二:CommandLineRunner接口
package org.springframework.boot; @FunctionalInterface public interface CommandLineRunner { /** * 用于運行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ù)將以字符串數(shù)組的形式傳遞給
run
方法。
實現(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ù)預熱啟動, 這里會在系統(tǒng)啟動后執(zhí)行"); } }
3、區(qū)別
- CommandLineRunner在ApplicationRunner之后被調(diào)用,也是在所有的ApplicationContext上下文都刷新和加載完成后執(zhí)行。但是,與ApplicationRunner不同的是,CommandLineRunner#run方法執(zhí)行之前,SpringApplication#run方法的參數(shù)也會被作為命令行參數(shù)傳遞給run方法。
- 如果需要訪問命令行參數(shù)和選項,或者需要在所有Bean初始化之前執(zhí)行特定的操作,你可以選擇使用ApplicationRunner。如果你只需要在所有Bean初始化之后執(zhí)行某些操作,你可以使用CommandLineRunner。
無論你選擇使用ApplicationRunne
還是CommandLineRunner
,它們都提供了在Spring Boot項目啟動時執(zhí)行自定義邏輯的能力。你可以根據(jù)實際需求選擇適合的接口來實現(xiàn)項目預熱或其他操作。
以上就是SpringBoot實現(xiàn)數(shù)據(jù)預熱的方式小結的詳細內(nèi)容,更多關于SpringBoot數(shù)據(jù)預熱的資料請關注腳本之家其它相關文章!
相關文章
Spring Cloud Zuul路由網(wǎng)關服務過濾實現(xiàn)代碼
這篇文章主要介紹了Spring Cloud Zuul路由網(wǎng)關服務過濾實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04Spring Security OAuth2集成短信驗證碼登錄以及第三方登錄
這篇文章主要介紹了Spring Security OAuth2集成短信驗證碼登錄以及第三方登錄,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04