1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        使用SpringBoot的CommandLineRunner遇到的坑

        共 13580字,需瀏覽 28分鐘

         ·

        2021-04-25 13:10

        來源:blog.csdn.net/zwq_zwq_zwq/article/details/81059017

        使用場景

        再應(yīng)用程序開發(fā)過程中,往往我們需要在容器啟動的時候執(zhí)行一些操作。Spring Boot中提供了CommandLineRunner和ApplicationRunner兩個接口來實現(xiàn)這樣的需求。

        兩個接口的不同

        參數(shù)不同,其他大體相同,可根據(jù)實際需求選擇合適的接口使用。CommandLineRunner接口中run方法的參數(shù)為String數(shù)組,ApplicationRunner中run方法的參數(shù)為ApplicationArguments。

        特殊的場景

        在啟動項目時,有時候我們所做的操作可能不是一次性的操作,有可能循環(huán)查詢數(shù)據(jù)庫,根據(jù)結(jié)果來處理不同的業(yè)務(wù),亦或是監(jiān)聽消息隊列……

        遇到的坑

        看下面一個例子,我們啟動一個spring boot項目,正常啟動情況下,項目啟動后會打印啟動時間。如下圖所示

        2018-07-16 01:48:22.378  INFO 9164 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
        2018-07-16 01:48:22.386  INFO 9164 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
        2018-07-16 01:48:22.386  INFO 9164 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
        2018-07-16 01:48:22.396  INFO 9164 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
        2018-07-16 01:48:22.417  INFO 9164 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
        2018-07-16 01:48:22.546  INFO 9164 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
        2018-07-16 01:48:22.555  INFO 9164 --- [           main] com.hello.word.WordParseApplication      : Started WordParseApplication in 3.811 seconds (JVM running for 4.486)

        下面我們模擬一下啟動項目時使用CommandLineRunner,有人說CommandLineRunner是項目啟動完成后才調(diào)用的,我們看看現(xiàn)象。

        @Component
        public class RunService  implements CommandLineRunner {
         
            public void run(String... strings){
                int i =0;
                while(true){
                    i++;
                        try {
                            Thread.sleep(10000);
                            System.out.println("過去了10秒鐘……,i的值為:"+i);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if(i==4){ //第40秒時拋出一個異常
                            throw new RuntimeException();
                        }
                        continue;
                }
            }
        }

        再次啟動spring boot 項目,看看日志,直接報錯,啟動異常了。

        2018-07-16 01:56:43.703  INFO 7424 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
        2018-07-16 01:56:43.703  INFO 7424 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
        2018-07-16 01:56:43.722  INFO 7424 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
        2018-07-16 01:56:43.750  INFO 7424 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
        2018-07-16 01:56:43.885  INFO 7424 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
        過去了10秒鐘……,i的值為:1
        過去了10秒鐘……,i的值為:2
        過去了10秒鐘……,i的值為:3
        過去了10秒鐘……,i的值為:4
        2018-07-16 01:57:23.939  INFO 7424 --- [           main] utoConfigurationReportLoggingInitializer : 
         
        Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
        2018-07-16 01:57:23.973 ERROR 7424 --- [           main] o.s.boot.SpringApplication               : Application startup failed
         
        java.lang.IllegalStateException: Failed to execute CommandLineRunner
         at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
         at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
         at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
         at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
         at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
         at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
         at com.hello.word.WordParseApplication.main(WordParseApplication.java:15) [classes/:na]
        Caused by: java.lang.RuntimeException: null
         at com.zhangwq.service.RunService.run(RunService.java:24) ~[classes/:na]
         at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
         ... 6 common frames omitted
         
        2018-07-16 01:57:23.975  INFO 7424 --- [           main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@14a4e18: startup date [Mon Jul 16 01:56:39 CST 2018]; root of context hierarchy
        2018-07-16 01:57:23.975  INFO 7424 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 2147483647
        2018-07-16 01:57:23.975  INFO 7424 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
         
        Process finished with exit code 1

        說明啟動CommandLineRunner的執(zhí)行其實是整個應(yīng)用啟動的一部分,沒有打印最后的啟動時間,說明項目是在CommandLineRunner執(zhí)行完成之后才啟動完成的。此時CommandLineRunner的run方法執(zhí)行的是一個循環(huán),循環(huán)到第四次的時候,拋出異常,直接影響主程序的啟動。(搜索公眾號Java知音,回復(fù)“2021”,送你一份Java面試題寶典)

        填坑

        這樣的問題該如何解決呢?這個操作影響了主線程,那么我們是否可以重新開啟一個線程,讓他單獨去做我們想要做的操作呢。

        @Component
        public class RunService  implements CommandLineRunner {
         
            public void run(String... strings){
                new Thread(){
                    public void run() {
                        int i = 0;
                        while (true) {
                            i++;
                            try {
                                Thread.sleep(10000);
                                System.out.println("過去了10秒鐘……,i的值為:" + i);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if (i == 4) { //第40秒時拋出一個異常
                                throw new RuntimeException();
                            }
                            continue;
                        }
                    }
                }.start();
            }
        }

        我們再看看這次的日志是什么樣的

        2018-07-16 02:05:52.680  INFO 7148 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
        2018-07-16 02:05:52.680  INFO 7148 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
        2018-07-16 02:05:52.695  INFO 7148 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
        2018-07-16 02:05:52.717  INFO 7148 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
        2018-07-16 02:05:52.815  INFO 7148 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
        2018-07-16 02:05:52.819  INFO 7148 --- [           main] com.hello.word.WordParseApplication      : Started WordParseApplication in 3.406 seconds (JVM running for 4.063)
        過去了10秒鐘……,i的值為:1
        過去了10秒鐘……,i的值為:2
        過去了10秒鐘……,i的值為:3
        過去了10秒鐘……,i的值為:4
        Exception in thread "Thread-10" java.lang.RuntimeException
         at com.zhangwq.service.RunService$1.run(RunService.java:26)

        此時CommandLineRunner執(zhí)行的操作和主線程是相互獨立的,拋出異常并不會影響到主線程。程序打印了啟動時間,并且CommandLineRunner中run方法報錯后,應(yīng)用程序并沒有因為異常而終止。填坑成功。

        最近給大家找了  JVM學(xué)習(xí)視頻


        資源,怎么領(lǐng)?。?/span>


        掃二維碼,加我微信,回復(fù):JVM

         注意,不要亂回復(fù) 

        沒錯,不是機器人
        記得一定要等待,等待才有好東西
        瀏覽 42
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            欧美黑人色情理伦片奴役 | 天天日天天操天天色 | 在线亚洲天堂 | 国产精品免费久久久久 | 国产又大又粗又长的视频 | 台湾午夜成人影院 | 美女张开腿给男人捅 | 欧美成人一区二区三区电影 | 免费国产网站 | 天天撸网站 |