SpringBoot 熱部署 Scheduled 定時任務器 全局異常攔截


一、SpringBoot單元測試

1、引入啟動器

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
</dependency>

<font color=red>注意:不需要引入junit的jar包</font>

2、測試方式1

import org.junit.Test;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ApplicationApp.class})
public class MyTest {

   @Autowired
   private IUserService userService;

   @Test
   public void userTest(){
       System.out.println(userService.findUser());
  }
}

3、測試方式2


import org.junit.jupiter.api.Test;  //注意junit包名

@SpringBootTest
public class MyTest {

   @Autowired
   private IUserService userService;

   @Test
   public void userTest(){
       System.out.println(userService.findUser());
  }
}

<font color=red>提示:測試來必須和啟動類在同一個包或子包下</font>

 

二、SpringBoot異常處理

1、默認方式

SpringBoot 默認的處理異常的機制:SpringBoot 默認的已經提供了一套處理異常的機制。一旦程序中出現了異常 SpringBoot 向src/main/resources/templates目錄下的/error 的 url 發送請求。在 springBoot 中提供了一個叫 BasicErrorController 來處理/error 請求,然后跳轉到默認顯示異常的頁面來展示異常信息。

  • 在src/main/resources/ templates創建error.html頁面


    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
       <meta charset="UTF-8">
       <title>錯誤提示頁面</title>
    </head>
    <body>
    出錯了,請與管理員聯系。。。
    </body>
    </html>
  • 修改controller


    @Controller
    public class HelloController {
       @RequestMapping("show")
       public String showInfo(){
          int i=1/0;
           return "index";
      }
    }

    當我們在瀏覽器訪問http://localhost/show時,會報異常,此時直接跳轉到error.html頁面

2、@ExceptionHandle 注解方式

在controller當前類中添加方法來捕獲當前類拋出的異常,從而進行處理,該方法上添加@ExceptionHandler注解

  • 在resources/templates目錄下創建error1.html頁面


    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
       <meta charset="UTF-8">
       <title>錯誤提示頁面-ArithmeticException</title>
    </head>
    <body>
      出錯了,請與管理員聯系。。。
       <span th:text="${error}"></span>
    </body>
    </html>
  • 修改controller


    @Controller
    public class HelloController {
       @RequestMapping("show")
       public String showInfo(){
          int i=1/0;
           return "index";
      }

       /**
        * 異常處理方法
        * @param e
        * @return
        */
       @ExceptionHandler(value = {java.lang.ArithmeticException.class})
       public ModelAndView arithmeticExceptionHandler(Exception e) {
           ModelAndView model = new ModelAndView();
           model.addObject("error", e.toString());
           model.setViewName("error1");  //邏輯視圖名
           return model;
      }
    }

3、@ControllerAdvice方式

自定義一個類GlobalException,並添加注解 @ControllerAdvice,或者@RestControllerAdvice, 在處理異常的方法上面添加@ExceptionHandler注解並在value中添加要處理的異常


@ControllerAdvice
public class GlobalException {
   /**
    * java.lang.ArithmeticException
    * 該方法需要返回一個 ModelAndView:目的是可以讓我們封裝異常信息以及視
    * 圖的指定
    * 參數 Exception e:會將產生異常對象注入到方法中
    */
   @ExceptionHandler(value = {ArithmeticException.class})
   public ModelAndView arithmeticExceptionHandler(Exception e) {
       ModelAndView mv = new ModelAndView();
       mv.addObject("error", e.toString());
       mv.setViewName("error");
       return mv;
  }

   /**
    * java.lang.NullPointerException
    * 該方法需要返回一個 ModelAndView:目的是可以讓我們封裝異常信息以及視
    * 圖的指定
    * 參數 Exception e:會將產生異常對象注入到方法中
    */
   @ExceptionHandler(value = {NullPointerException.class})
   public ModelAndView nullPointerExceptionHandler(Exception e) {
       ModelAndView mv = new ModelAndView();
       mv.addObject("error", e.toString());
       mv.setViewName("error1");
       return mv;
  }
}

4、全局異常解析器

自定義一個配置類,創建一個全局異常SimpleMappingExceptionResolver解析器的bean對象到spring容器中,有spring來管理


@Configuration
public class GlobalException {
   /**
    * 該方法必須要有返回值。返回值類型必須是:
    * SimpleMappingExceptionResolver
    */
   @Bean
   public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
       SimpleMappingExceptionResolver resolver = new  SimpleMappingExceptionResolver();
       Properties mappings = new Properties();
       /**
        * 參數一:異常的類型,注意必須是異常類型的全名
        * 參數二:邏輯視圖名稱
        */
       mappings.put("java.lang.ArithmeticException", "error1");
       mappings.put("java.lang.NullPointerException", "error2");
       //設置異常與視圖映射信息的
       resolver.setExceptionMappings(mappings);
       return resolver;
  }
}

 

三、SpringBoot定時任務

Scheduled 定時任務器:是 Spring3.0 以后自帶的一個定時任務器

1、 引入依賴


<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2、編寫定時任務


@Component
public class ScheduledDemo {

   /**
    *定時任務方法
    * @Scheduled:設置定時任務 cron 屬性:cron 表達式。定時任務觸發是時間的一個字符串表達形式
    */
   @Scheduled(cron = "0/2 * * * * ?")
   //@Scheduled(initialDelay = 1000 * 10,fixedRate = 1000 * 5) //fixedRate = 1000 *5表示每5秒執行一次
   public void scheduledMethod() {
       System.out.println("定時器被觸發" + new Date());
  }
}

3、 開啟定時任務注解

在啟動類中添加@EnableScheduling注解


/**
* 啟動類
*/
@SpringBootApplication
@MapperScan("cn.woniu.dao")//掃描dao
@EnableScheduling //開啟定時任務
public class ApplicationApp {
   public static void main(String[] args) {
       SpringApplication.run(ApplicationApp.class,args);
  }
}

4、Cron 表達式


Cron 表達式是一個字符串,分為 6 或 7 個域,每一個域代表一個含義;
Cron 從左到右(用空格隔開): 秒   分   小時   月份中的日期   月份   星期中的日期   年份

Cron 有如下兩種語法格式:

  • Seconds Minutes Hours Day Month Week Year

  • Seconds Minutes Hours Day Month Week

序號 說明 取值 表達式
1 0-59 -*/
2 分鍾 0-59 -*/
3 小時 0-23 -*/
4 1-31 -*/LWC
5 1-12 -*/
6 星期 1-7 -*?/LC#
7 年(可選) 1970-2099 -*/

Cron 表達式的時間字段除允許設置數值外,還可使用一些特殊的字符,提供列表、范圍、通配符等功,如下:

  • 星號(*):可用在所有字段中,表示對應時間域的每一個時刻,例如,在分鍾字段時,表示“每分鍾”;

  • 問號(?):該字符只在日期和星期字段中使用,它通常指定為“無意義的值”,相當於占位符;

  • 減號(-):表達一個范圍,如在小時字段中使用“10-12”,則表示從 10 到 12 點,即 10,11,12;

  • 逗號(,):表達一個列表值,如在星期字段中使用“MON,WED,FRI”,則表示星期一,星期三和星期五;

  • 斜杠(/):x/y 表達一個等步長序列,x 為起始值,y 為增量步長值。如在分鍾字段中使用 0/15,則表示為 0,15,30 和 45 秒,而 5/15 在分鍾字段中表示 5,20,35,50,你也可以使用*/y,它等同於 0/y;

  • L:該字符只在日期和星期字段中使用,代表“Last”的意思,但它在兩個字段中意思不同。L 在日期字段中,表示這個月份的最后一天,如一月的 31 號,非閏年二月的 28 號;如果 L 用在星期中,則表示星期六,等同於 7。但是,如果 L 出現在星期字段里,而且在前面有一個數值 X,則表示“這個月的最后 X 天”,例如,6L 表示該月的最后星期五;

  • W:該字符只能出現在日期字段里,是對前導日期的修飾,表示離該日期最近的工作日。例如 15W表示離該月 15 號最近的工作日,如果該月 15 號是星期六,則匹配 14 號星期五;如果 15 日是星期日,則匹配 16 號星期一;如果 15 號是星期二,那結果就是 15 號星期二。但必須注意關聯的匹配日期不能夠跨月,如你指定 1W,如果 1 號是星期六,結果匹配的是 3 號星期一,而非上個月最后的那天。W 字符串只能指定單一日期,而不能指定日期范圍;

  • LW 組合:在日期字段可以組合使用 LW,它的意思是當月的最后一個工作日;

  • 井號(#):該字符只能在星期字段中使用,表示當月某個工作日。如 6#3 表示當月的第三個星期五(6表示星期五,#3 表示當前的第三個),而 4#5 表示當月的第五個星期三,假設當月沒有第五個星期三,忽略不觸發;

  • C:該字符只在日期和星期字段中使用,代表“Calendar”的意思。它的意思是計划所關聯的日期,如果日期沒有被關聯,則相當於日歷中所有日期。例如 5C 在日期字段中就相當於日歷 5 日以后的第一天。1C 在星期字段中相當於星期日后的第一天。

案例說明:


@Scheduled(cron = "0 0 1 1 1 ?")//每年一月的一號的 1:00:00 執行一次
@Scheduled(cron = "0 0 1 1 1,6 ?") //一月和六月的一號的 1:00:00 執行一次
@Scheduled(cron = "0 0 1 1 1,4,7,10 ?") //每個季度的第一個月的一號的 1:00:00 執行一次
@Scheduled(cron = "0 0 1 1 * ?")//每月一號 1:00:00 執行一次
@Scheduled(cron="0 0 1 * * *") //每天凌晨 1 點執行一次

 

四、SpringBoot熱部署

SpringBoot執部署可以讓程序員修改代碼后不重新啟動服務器也能訪問到更新后的內容。

springboot熱部署有兩種方式:SpringLoader 插件、DevTools 工具;

1、使用 SpringLoader 進行項目熱部署

在 pom文件中添加插件配置

如果在插件中無法加載可以現在pom的dependencies中下載后再在插件中引入依賴


<build>
       <plugins>
           <!-- springloader 插件 -->
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
               <dependencies>
                   <dependency>
                       <groupId>org.springframework</groupId>
                       <artifactId>springloaded</artifactId>
                       <version>1.2.8.RELEASE</version>
                   </dependency>
               </dependencies>
           </plugin>
       </plugins>
   </build>

在主啟動類中,右鍵以debug模式啟動項目,訪問/show路徑,項目跳轉到index頁面,修改/show方法返回的值為“test”並且按 Ctr+shift+F9重新編譯文件,刷新頁面,發現沒有重新啟動項目也可以訪問到修改后的內容

2、DevTools 工具

a、SpringLoader 與 DevTools 的區別

  • SpringLoader:SpringLoader 在部署項目時使用的是熱部署的方式

  • DevTools:DevTools 在部署項目時使用的是重新部署的方式

修改pom


<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
</dependency>

b、修改idel 配置

file---Settings

 

 

ctr+alt+shift+"/"

 

 

啟動項目后發現修改后可以不用手動重新啟動項目就可以看到修改后的變化


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM