@Async Could not find unique TaskExecutor bean; NoUniqueBeanDefinitionException;

本文探讨了在项目启动或接口调用时遇到的异步任务配置冲突问题,具体表现为控制台报错CouldnotfinduniqueTaskExecutorbean。文章详细解释了错误原因,包括@Async注解方法名重复或同一异步任务被多个任务同时调用,并提供了两种解决方案:一是修改方法名,二是增加异步任务配置类。

异步任务,项目启动或接口调用,控制台报错:Could not find unique TaskExecutor bean;

或者报错:org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.core.task.TaskExecutor' available: expected single matching bean but found 2: applicationTaskExecutor,taskScheduler

原因为:@Async所注解的方法存在相同的方法名,或者同一个异步任务被多个任务同时调用

解决方法:

1、将@Async所注解的方法名修改为不同的方法名

2、增加异步任务配置类:

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @description 异步任务配置类,为防止异步任务如下错误:
 * No qualifying bean of type 'org.springframework.core.task.TaskExecutor' available:
 * expected single matching bean but found 2: applicationTaskExecutor,taskScheduler
 * @author: chenping
 * @create: 2020-01-17
 **/
@Configuration
@ComponentScan("cn.com.*.*.*.service")//异步任务所在的包
@EnableAsync //开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer {

    /**
     * @description:  实现AsyncConfigurer接口并重写getAsyncExecutor方法,
     *  并返回一个ThreadPoolTaskExecutor,这样我们就获得了一个基于线程池TaskExecutor
     * @param:
     * @return: java.util.concurrent.Executor
     * @author: chenping
     * @date: 2020/1/17
     **/
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(80);
        taskExecutor.setQueueCapacity(100);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值