异步


异步

在需要异步的方法上加上@Async

比如业务代码

@Service
public class AsyncService {
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理");
    }

}

在主应用上添加@EnableAsync

@SpringBootApplication
@EnableAsync
//开启异步注解
public class Springboot09TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }
}

测试Controller

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

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