项目中经常会遇到一些执行时间较长的任务,这个时候很容易就想到使用多线程来处理。由于这个需求太常用,因此我们的spring大佬就直接帮我们从框架层面实现。
实例代码:web接口异步
MutiThreadApplication
@SpringBootApplication
@EnableAsync //注意加这个注解,启动异步功能
public class MutiThreadApplication {
//配置系统线程池
@Bean
public Executor getExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(25);
executor.setAwaitTerminationSeconds(20000);
return executor;
}
public static void main(String[] args) {
SpringApplication.run(MutiThreadApplication.class, args);
}
}
TestController
package com.liao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.liao.service.TestService;
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
public String test() {
System.out.println("main:start");
testService.test();
System.out.println("main:end");
return "end";
}
}
TestService
package com.liao.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TestService {
@Async //此注解标识该方法要异步执行,spirng会启动一个线程异常执行该方法
public void test() {
System.out.println(Thread.currentThread().getName()+":start");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":end");
}
}
执行结果
web请求立刻返回结果。
系统日志如下:
main:start
main:end
getExecutor-1:start
getExecutor-1:end