Spring 异步线程池的使用

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

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
@EnableAsync
public 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;

@Service
public class AsyncServiceImpl implements AsyncService {

	@Override
	@Async  // 声明使用异步调用
	public void generateReport() {
		// 打印当前异步线程名称
		System.out.println("报表线程名称" + Thread.currentThread().getName());
	}
}

然后就可以在 controller 中调用了

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值