spring @async

本文介绍了两种自定义线程池的方式,包括通过`ThreadPoolExecutor`直接配置和使用`ThreadPoolTaskExecutor`。同时,文章讨论了Spring `@Async`注解失效的常见原因,并提供了详细的解决方案,如确保方法为public,从外部调用或通过获取对象的代理类进行内部调用。此外,还提供了一个实用工具类`SpringUtils`来获取Spring容器中的bean,以确保使用代理对象执行异步方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.自定义线程池-两种方式

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {
    private static final int CORE_POOL_SIZE = 3;

    @Override
    public Executor getAsyncExecutor() {
        return new ThreadPoolExecutor(CORE_POOL_SIZE, CORE_POOL_SIZE, 0,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("线程池执行任务发生异常", ex);
    }
}
@Configuration
@EnableAsync
class SpringAsyncConfigurer extends AsyncConfigurerSupport { 
  
  @Bean
  public ThreadPoolTaskExecutor asyncExecutor() { 
    ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); 
    threadPool.setCorePoolSize(3); 
    threadPool.setMaxPoolSize(3); 
    threadPool.setWaitForTasksToCompleteOnShutdown(true); 
    threadPool.setAwaitTerminationSeconds(60 * 15); 
    return threadPool; 
  } 
  
  @Override
  public Executor getAsyncExecutor() { 
    return asyncExecutor; 
} 
 
 @Override
  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  return (ex, method, params) -> ErrorLogger.getInstance().log(String.format("执行异步任务'%s'", method), ex);
}
}

 2.async失效注意点

1.没有在@SpringBootApplication启动类当中添加注解@EnableAsync注解。

2.异步方法使用注解@Async的返回值只能为void或者Future。

3.没有走Spring的代理类。因为@Transactional和@Async注解的实现都是基于Spring的AOP,而AOP的实现是基于动态代理模式实现的。那么注解失效的原因就很明显了,有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器。

解决方法:

这里具体说一下第三种情况的解决方法。

1.注解的方法必须是public方法。

2.方法一定要从另一个类中调用,也就是从类的外部调用,类的内部调用是无效的。

3.如果需要从类的内部调用,需要先获取其代理类,下面上代码

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 

@Component("springContextUtil")
public class SpringUtils implements ApplicationContextAware {
  private static ApplicationContext applicationContext = null;
 
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }
 
  @SuppressWarnings("unchecked")
  public static <T> T getBean(String beanId) {
    return (T) applicationContext.getBean(beanId);
  }
 
  public static <T> T getBean(Class<T> requiredType) {
    return (T) applicationContext.getBean(requiredType);
  }
  /**
   * Spring容器启动后,会把 applicationContext 给自动注入进来,然后我们把 applicationContext
   * 赋值到静态变量中,方便后续拿到容器对象
   * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringUtils.applicationContext = applicationContext;
  }
}
@Service
public class AsyncService{
 public void methodA(){
  ...
  AsyncService asyncServiceProxy = SpringUtil.getBean(AsyncService.class);
  asyncServiceProxy .methodB();
  ...
 }
  
 @Async
 public void methodB() {
  ...
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值