springboot中实现异步方法

开启配置线程池

package org.springblade.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 */
@EnableAsync
@Configuration
public class ThreadPoolTaskConfig {

	/**
	 * 核心线程数(默认线程数)
	 */
	private static final int CORE_POOL_SIZE = 5;
	/**
	 * 最大线程数
	 */
	private static final int MAX_POOL_SIZE = 10;
	/**
	 * 允许线程空闲时间(单位:默认为秒)
	 */
	private static final int KEEP_ALIVE_TIME = 5;
	/**
	 * 缓冲队列大小
	 */
	private static final int QUEUE_CAPACITY = 50;
	/**
	 * 线程池名前缀
	 */
	private static final String THREAD_NAME_PREFIX = "Async-Service-";

	/**
	 * bean的名称,默认为首字母小写的方法名
	 * 然后在用到的异步方法的地方,显式引用改线程池。
	 * 例如@Async("taskExecutor")
	 */
	@Bean("taskExecutor")
	public ThreadPoolTaskExecutor taskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(CORE_POOL_SIZE);
		executor.setMaxPoolSize(MAX_POOL_SIZE);
		executor.setQueueCapacity(QUEUE_CAPACITY);
		executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
		executor.setThreadNamePrefix(THREAD_NAME_PREFIX);

		// 线程池对拒绝任务的处理策略
		// CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		// 初始化
		executor.initialize();
		return executor;
	}

}

  

       
方法上加上@Async("taskExecutor")注解,在其他业务类中调用就可以实现异步调用

        @Override
	@Async("taskExecutor")
	public Boolean updateDoctorOrAssistantRedundanceInfo(BizUpdateDTO dto) {

		
		
       }

  

posted @ 2024-04-10 22:43  红尘沙漏  阅读(30)  评论(0编辑  收藏  举报