SpringBoot——任務

任務

1、異步任務

同步任務就是,A調用了B方法,必須要得B執行完了之後才能執行,如果B方法執行的很慢,A頁必須等待。

鑑於這種方法有時候會很低效,所以就有了異步執行,A調用B方法之後,會再開一個線程去執行B,不會影響A的執行。

在SpringBoot中要想實現異步任務十分簡單,接下來我們先寫一個不是異步方法的代碼,

@Service
public class AsyncService {
  
    public void hello() throws InterruptedException {
        Thread.sleep(5000);	//測試方法,我們讓線程失眠5秒
        System.out.println("處理數據中...");
    }

}

編寫controller層如下:

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello() throws InterruptedException {
        asyncService.hello();	//調用同步方法
        return "hello";
    }

}

運行項目,在瀏覽器中輸入 http://localhost:8080/hello ,可以看到在過了 5 秒之後纔會輸出 hello

現在我們來更改 AsyncService.java 中的代碼:

@Service
public class AsyncService {
    //告訴Spring這是一個異步方法
    @Async
    public void hello() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("處理數據中...");
    }
}

並且在 UmserverApplication.java 中開啓異步註解:

@SpringBootApplication
@EnableAsync
public class UmserverApplication {

	public static void main(String[] args) {
		SpringApplication.run(UmserverApplication.class, args);
	}

}

再次執行,就可以馬上看到 hello ,但是在 5 秒之後控制檯輸出 處理數據中...

1.1 配置

如果你在 context 中定義了一個 Executor ,那麼異步任務就會使用它。

線程池使用8個核心線程,當然也會根據任務的多少增加或者減少。這些默認的配置能夠使用 spring.task.execution 命名空間來調整,例如:

spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s

上面的配置使線程池使用了一個受限的 queue ,當 queue 滿的時候(達到了100個任務),線程數就會增加,但是最大也只會到 16 個。線程空閒10 秒(而不是默認的 60 秒)時,線程就會被回收。

2、定時任務

要使用定時任務也是十分的簡單,如下:

在方法上添加上 @Scheduled 註解,

@Service
public class MailSend {
  	/*cron的詳細配置請看下面*/
    @Scheduled(cron = "0-4 * * * * 1-6")
    public void hello() throws InterruptedException {
        System.out.println("hello...");
    }
}

並且在 UmserverApplication.java 中添加上 @EnableScheduling 註解即可。

@SpringBootApplication
@EnableAsync
@EnableScheduling
public class UmserverApplication {

	public static void main(String[] args) {
		SpringApplication.run(UmserverApplication.class, args);
	}

}

啓動項目後,在每分鐘的 0-4 秒時控制檯會打印 hello...

關於 cron 的值:

字段 允許值 允許的特殊字符
0-59 , - * /
0-59 , - * /
小時 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 , - * /
星期 1-7 , - * ? / L C #
特殊字符 代表含義
, 枚舉
- 區間
* 任意
/ 步長
? 日/星期衝突匹配
L 最後
W 工作日
C 和calendar聯繫後計算過的值
# 星期, 4#2 ,第2個星期四
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章