溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

SpringBoot程序預(yù)裝載數(shù)據(jù)怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2022-04-29 10:17:19 來(lái)源:億速云 閱讀:149 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“SpringBoot程序預(yù)裝載數(shù)據(jù)怎么實(shí)現(xiàn)”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“SpringBoot程序預(yù)裝載數(shù)據(jù)怎么實(shí)現(xiàn)”文章能幫助大家解決問(wèn)題。

    簡(jiǎn)介

    在項(xiàng)目實(shí)際的開(kāi)發(fā)過(guò)程中,有時(shí)候會(huì)遇到需要在應(yīng)用程序啟動(dòng)完畢對(duì)外提供服務(wù)之前預(yù)先將部分?jǐn)?shù)據(jù)裝載到緩存的需求。

    適用場(chǎng)景

    • 預(yù)裝載應(yīng)用級(jí)別數(shù)據(jù)到緩存:如字典數(shù)據(jù)、公共的業(yè)務(wù)數(shù)據(jù)

    • 系統(tǒng)預(yù)熱

    • 心跳檢測(cè):如在系統(tǒng)啟動(dòng)完畢訪問(wèn)一個(gè)外服務(wù)接口等場(chǎng)景

    常用方法

    • ApplicationEvent

    • CommandLineRunner

    • ApplicationRunner

    ApplicationEvent

    應(yīng)用程序事件,就是發(fā)布訂閱模式。在系統(tǒng)啟動(dòng)完畢,向應(yīng)用程序注冊(cè)一個(gè)事件,監(jiān)聽(tīng)者一旦監(jiān)聽(tīng)到了事件的發(fā)布,就可以做一些業(yè)務(wù)邏輯的處理了。

    既然是發(fā)布-訂閱模式,那么訂閱者既可以是一個(gè),也可以是多個(gè)。

    定義event

    import org.springframework.context.ApplicationEvent;
    public class CacheEvent   extends ApplicationEvent {
        public CacheEvent(Object source) {
            super(source);
        }
    }

    定義listener

    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.ApplicationListener;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    @Slf4j
    @Component
    public class CacheEventListener implements ApplicationListener<CacheEvent> {
        @Autowired
        private MaskingService maskingService;
        @Autowired
        private RedisCache redisCache;
        @Override
        public void onApplicationEvent(CacheEvent cacheEvent) {
            log.debug("CacheEventListener-start");
            List<SysMasking> maskings = maskingService.selectAllSysMaskings();
            if (!CollectionUtils.isEmpty(maskings)) {
                log.debug("CacheEventListener-data-not-empty");
                Map<String, List<SysMasking>> cacheMap = maskings.stream().collect(Collectors.groupingBy(SysMasking::getFieldKey));
                cacheMap.keySet().forEach(x -> {
                    if (StringUtils.isNotEmpty(x)) {
                        log.debug("CacheEventListener-x={}", x);
                        List<SysMasking> list = cacheMap.get(x);
                        long count = redisCache.setCacheList(RedisKeyPrefix.MASKING.getPrefix() + x, list);
                        log.debug("CacheEventListener-count={}", count);
                    } else {
                        log.debug("CacheEventListener-x-is-empty");
                    }
                });
            } else {
                log.debug("CacheEventListener-data-is-empty");
            }
            log.debug("CacheEventListener-end");
        }
    }

    注冊(cè)event

    @Slf4j
    @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
    public class BAMSApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(BAMSApplication.class, args);
            log.debug("app-started");
            context.publishEvent(new CacheEvent("處理緩存事件"));
        }
    }

    CommandLineRunner

    通過(guò)實(shí)現(xiàn) CommandLineRunner 接口,可以在應(yīng)用程序啟動(dòng)完畢,回調(diào)到指定的方法中。

    package com.ramble.warmupservice.runner;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    @Slf4j
    @Component
    public class CacheCommandLineRunner implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            log.debug("CacheCommandLineRunner-start");
            log.debug("CacheCommandLineRunner-參數(shù)={}", args);
            // 注入業(yè)務(wù) service ,獲取需要緩存的數(shù)據(jù)
            // 注入 redisTemplate ,將需要緩存的數(shù)據(jù)存放到 redis 中
            log.debug("CacheCommandLineRunner-end");
        }
    }

    ApplicationRunner

    同CommandLineRunner 類(lèi)似,區(qū)別在于,對(duì)參數(shù)做了封裝。

    package com.ramble.warmupservice.runner;
    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.stereotype.Component;
    @Slf4j
    @Component
    public class CacheApplicationRunner implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {
            log.debug("CacheApplicationRunner-start");
            log.debug("CacheApplicationRunner-參數(shù)={}", JSON.toJSONString(args));
            // 注入業(yè)務(wù) service ,獲取需要緩存的數(shù)據(jù)
            // 注入 redisTemplate ,將需要緩存的數(shù)據(jù)存放到 redis 中
            log.debug("CacheApplicationRunner-end");
        }
    }

    測(cè)試

    上述代碼在idea中啟動(dòng),若不帶參數(shù),輸出如下:

    2022-04-28 15:44:00.981  INFO 1160 --- [           main] c.r.w.WarmupServiceApplication           : Started WarmupServiceApplication in 1.335 seconds (JVM running for 2.231)
    2022-04-28 15:44:00.982 DEBUG 1160 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-start
    2022-04-28 15:44:01.025 DEBUG 1160 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-參數(shù)={"nonOptionArgs":[],"optionNames":[],"sourceArgs":[]}
    2022-04-28 15:44:01.025 DEBUG 1160 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-end
    2022-04-28 15:44:01.025 DEBUG 1160 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-start
    2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-參數(shù)={}
    2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-end
    2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-start
    2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-參數(shù)=ApplicationEvent-->緩存系統(tǒng)數(shù)據(jù)
    2022-04-28 15:44:01.029 DEBUG 1160 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-end
    Disconnected from the target VM, address: '127.0.0.1:61320', transport: 'socket'
    Process finished with exit code 130

    若使用 java -jar xxx.jar --server.port=9009 啟動(dòng),則輸入如下:

    2022-04-28 16:02:05.327  INFO 9916 --- [           main] c.r.w.WarmupServiceApplication           : Started WarmupServiceApplication in 1.78 seconds (JVM running for 2.116)
    2022-04-28 16:02:05.329 DEBUG 9916 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-start
    2022-04-28 16:02:05.393 DEBUG 9916 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-參數(shù)={"nonOptionArgs":[],"optionNames":["server.port"],"sourceArgs":["--server.port=9009"]}
    2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-end
    2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-start
    2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-參數(shù)=--server.port=9009
    2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-end
    2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-start
    2022-04-28 16:02:05.396 DEBUG 9916 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener- 參數(shù)=ApplicationEvent-->緩存系統(tǒng)數(shù)據(jù)
    2022-04-28 16:02:05.396 DEBUG 9916 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-end

    執(zhí)行順序

    從上面測(cè)試的輸出,可以看到三種方式執(zhí)行的順序?yàn)椋?br/>ApplicationRunner--->CommandLineRunner--->ApplicationEvent

    另外,若同時(shí)定義多個(gè)runner,可以通過(guò)order來(lái)指定他們的優(yōu)先級(jí)。

    關(guān)于“SpringBoot程序預(yù)裝載數(shù)據(jù)怎么實(shí)現(xiàn)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI