学习视频: https://www.bilibili.com/video/BV1PE411i7CV?p=51
1.1 异步任务
在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以一般会采用多线程的方式去处理这些任务。
编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况。
1、项目目录
2、编写AsyncService
package cn.guardwhy.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello(){
try {
// 休眠3秒
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 输出结果
System.out.println("数据处理中.....");
}
}
3、编写AsyncController类
package cn.guardwhy.controller;
import cn.guardwhy.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello(); // 停止3S,转圈
return "success";
}
}
4、启动项目,访问http://localhost:8080/hello进行测试,3秒后出现了success,这是同步等待的情况。
5、 给hello方法添加@Async注解
,可以在用户直接得到消息,在后台使用多线程的方式进行处理。
package