Springboot异步任务async注解的使用

我们在程序执行的时候,经常需要通过异步来处理一些任务,比如程序执行完后,给用户异步发一份邮件。今天介绍下springboot自带异步注解async的使用。

1、项目创建过程忽略,具体目录请看下面截图

2、在service文件夹下创建需要执行的service服务文件,如AsyncService.java

这里需要注意在异步执行的方法上加入注解 @Async

 1 package com.ymy.service;
 2 
 3 import org.springframework.scheduling.annotation.Async;
 4 import org.springframework.stereotype.Service;
 5 
 6 @Service
 7 public class AsyncService {
 8 
 9     @Async
10     public void hello() {
11         try {
12             Thread.sleep(3000);
13         } catch (InterruptedException e) {
14             e.printStackTrace();
15         }
16         System.out.print("数据处理中。。。。。");
17     }
18 }

3、在controller文件夹下创建调用文件,TestController.java

 1 package com.ymy.controller;
 2 
 3 import com.ymy.service.AsyncService;
 4 import lombok.extern.slf4j.Slf4j;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.web.bind.annotation.GetMapping;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.RestController;
10 
11 import javax.annotation.Resource;
12 
13 @RestController
14 @Slf4j
15 public class TestController {
16 
17     @Autowired
18     AsyncService asyncService;24 
25     @GetMapping("hello")
26     public String hello() {
27         asyncService.hello();
28         return "Ok14567";
29     }
30 }

4、最后需要在启动文件加入注解关键字 @EnableAsync

 1 package com.ymy;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.scheduling.annotation.EnableAsync;
 6 
 7 @SpringBootApplication
 8 @EnableAsync
 9 public class SpingBootDockerApplication {
10 
11     public static void main(String[] args) {
12         SpringApplication.run(SpingBootDockerApplication.class, args);
13     }
14 
15 }

 

posted @ 2022-05-10 11:12  北京流浪儿  阅读(464)  评论(0编辑  收藏  举报