springBoot项目中任务---开启异步任务

Controller层代码:

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();//停止三秒,转圈
        return "ok";
    }
}

Service层代码:

@Service
public class AsyncService {

    //告诉spring这是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }
}

启动类上加上注解;

@EnableAsync //开启异步注解功能
@SpringBootApplication
public class DemoApplication {

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

}

总结:就是两步;第一步,在方法上加上@Async注解;第二步,在启动类上加上@EnableAsync即可;

效果,进入hello方法,浏览器不会立刻进入,会转圈三秒再显示ok;

 
原文地址:https://www.cnblogs.com/xie-qi/p/14711323.html