SpringBoot-异步任务

在springboot中开启异步任务十分简单只需要两步

  1. 在主启动类中添加注解@EnableAsync

    1
    2
    3
    4
    5
    6
    7
    8
    @SpringBootApplication
    @EnableAsync // 开启异步注解功能
    public class Springboot08TestApplication {

    public static void main(String[] args) {
    SpringApplication.run(Springboot08TestApplication.class, args);
    }
    }
  2. 在服务中使用注解@Async表示该任务为异步

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Service
    public class AsyncService {

    @Async // 告诉spring这是异步的方法
    public void hello(){
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("doing");
    }
    }

这样的话,在controller中,程序遇见异步服务将直接执行下一步

1
2
3
4
5
6
7
8
9
10
11
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;

@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}

结果是ok将会先行返回,三秒后doing才会被打印