当用户在前台页面使用邮件发送功能,这个请求会交于后端处理,如果采用同步任务,在这段时间内,前台的页面都是等待状态的,用户还会以为卡死,耗费时间和资源。在SpringBoot中开启异步任务很简单,两个注解搞定 @EnableAsyncAsync

在执行异步任务之前需要在启动类上开启异步注解功能

1.开启异步注解功能

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

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

}

2.在Service层编写需要执行的异步任务方法。

@Service
public class AsyncService {
    @Async  //告诉Spring这是一个异步的方法
    public void hello(){
        try {
            Thread.sleep(5000);//休眠5s
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }
}

3.Controller层调用Service层方法。

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();   //执行业务层hello方法:停止5s
        return "hello";
    }
}

执行结果:执行此方法后,控制台会直接打印内容,而无需等待时间。  

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐