欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

异步任务

程序员文章站 2022-06-12 20:35:35
...

Spring Boot异步任务

  1. 启动程序加上@EnableAsync注解
  2. 方法上面加上@Async注解

代码:

@EnableAsync
@SpringBootApplication
public class Springboot4TaskApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(Springboot4TaskApplication.class, args);
    }
}
@RestController
public class AsyncController 
    
    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "success";
    }

}
@Service
public class AsyncService {
    
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("format data ....");
    }
}