SpringBoot中的常见任务-----异步任务


编写业务层,写一个方法,手动睡眠三秒

//告诉Spring这是一个异步的方法,还需要在main方法中开始异步请求,也就是加注解
@Async//注解的作用:告诉Spring这是一个异步方法,自己开一个线程在后台跑
@Service
public class AsyncService {
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("数据正在处理...");
    }
}

编写controller层,调用service层里面的方法

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;


    @RequestMapping("/hello")
    public String hello(){
        //开启多线程之后,此方法用里另一个线程执行,先返回ok,提升用户体验
        asyncService.hello();//睡眠三秒,转圈
        return "Ok";
    }

}

需要在main方法中开启异步注解功能

//开启异步注解功能
@EnableAsync//EnableXxx:就是开始某个功能
@SpringBootApplication
public class Springboot09TestApplication {

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

}

以上就是异步任务的步骤