在系统需要进行一些比较耗时的操作,比如用户注册后要调用邮件服务器给用户发送个邮件,又比如上传一个大数据量的 excel 并导入到数据库。如果后端的这些工作比较耗时,那么前台的页面便会一直处于等待状态,让用户会以为页面卡死了。
这里我们使用 java 线程池 ExecutorService,首先在项目中添加如下配置类,其作用在于 Spring 启动时自动加载一个 ExecutorService 对象。
1
2
3
4
5
6
7
8
|
@Configuration public class ThreadPoolConfig { @Bean public ExecutorService executorService() { return Executors.newCachedThreadPool(); } } |
这里我们实现 Runnable 接口来创建一个异步任务,里面代码很简单,就是等待个 5 秒再结束:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class EmailRunnable implements Runnable { private String name; public EmailRunnable(String name) { this .name = name; } @Override public void run() { System.out.println( "正在给" + name + "发送邮件......" ); try { Thread.sleep( 5000 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "邮件发送完毕" ); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@RestController public class HelloController { @Autowired ExecutorService executorService; @GetMapping ( "/hello" ) public void hello() { System.out.println( "hello start" ); executorService.execute( new EmailRunnable( "hangge" )); System.out.println( "hello end" ); } } |
(2)通过浏览器访问 /hello 接口,可以看到控制台输出如下:
SpringBoot - 使用ExecutorService线程池执行异步任务教程(Runnable任务为例)
原文:https://www.cnblogs.com/ygfsy/p/14041522.html