Spring 异步线程池的使用
发布日期:2021-08-31 01:31:18 浏览次数:3 分类:技术文章

本文共 1486 字,大约阅读时间需要 4 分钟。

hot3.png

只需要创建一个 Java 配置类, 实现 AsyncConfigurer 接口, 实现 getAsyncExecutor 方法返回线程池. 在 java 配置文件类上加注解 @EnableAsync 开启异步可用, 然后就可以在 service 方法上使用注解 使用异步调用

1. 创建一个 java 配置类文件.

package com.codingos.springboot.test.config;import java.util.concurrent.Executor;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.AsyncConfigurer;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;@Configuration@EnableAsyncpublic class AsyncConfig implements AsyncConfigurer {	/**	 * 定义线程池	 */	@Override	public Executor getAsyncExecutor() {		// 定义线程池		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();		// 设置核心线程		taskExecutor.setCorePoolSize(10);		// 设置最大线程		taskExecutor.setMaxPoolSize(30);		// 设置线程队列最大线程数		taskExecutor.setQueueCapacity(2000);		// 初始化		taskExecutor.initialize();		return taskExecutor;	}}

2. 创建异步服务 service

package com.codingos.springboot.test.service.impl;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;import com.codingos.springboot.test.service.AsyncService;@Servicepublic class AsyncServiceImpl implements AsyncService {	@Override	@Async  // 声明使用异步调用	public void generateReport() {		// 打印当前异步线程名称		System.out.println("报表线程名称" + Thread.currentThread().getName());	}}

然后就可以在 controller 中调用了

要注意的是:异步配置文件类上要使用 @EnableAsync 注解,异步 service 的方法上使用 注解

转载于:https://my.oschina.net/zdtdtel/blog/3015025

转载地址:https://blog.csdn.net/weixin_34056162/article/details/91926524 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:香蕉派BPI-G1 原理图正式公开发布
下一篇:LeetCode-Rotate Array

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月20日 08时14分37秒