- 首先创建线程池,下面代码
- 配置文件配置
#线程池配置
task.queue.corePoolSize=10
task.queue.maxPoolSize=30
task.queue.queueCapacity=8
task.queue.keepAlive=60`
@EnableAsync(proxyTargetClass = true)
@Configuration
public class AsycTaskExecutorConfig {
@Value("${task.queue.corePoolSize}")
private int corePoolSize;
@Value("${task.queue.maxPoolSize}")
private int maxPoolSize;
@Value("${task.queue.queueCapacity}")
private int queueCapacity;
@Value("${task.queue.keepAlive}")
private int keepAlive;
@Bean
public Executor taskQueueExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("线程-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setKeepAliveSeconds(keepAlive);
executor.initialize();
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
- 自己创建一个类,里面放置异步方法,一定要加上 @Async注解
@Component
public class AsyThread {
@Async
public void sendMessage() {
System.out.println("马上执行异步消息了");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("---------发消息了---------"+Thread.currentThread().getName());
}
}
- 这里我们就可以在controller里面正常写我们的代码,我写了个简单例子
@Autowired
AsyThread asyThread;
@Autowired
DemoService demoService;
@RequestMapping("testDemo")
public void testDemo(){
asyThread.sendMessage();
User user = demoService.findUser();
System.out.println(user.toString() + "------用户对象------");
System.out.println("当前线程"+Thread.currentThread().getName());
}
- 演示效果(没有加 @Async注解)
![没有实现异步效果](https://i-blog.csdnimg.cn/blog_migrate/6c7cae6b7e3aebd0e2a5e13a65f178e7.png)
- 演示效果(加 @Async注解)
![实现了异步效果](https://i-blog.csdnimg.cn/blog_migrate/dff4dffe8144f0483026d82a55ee3471.png)