@Async 使用和失效情况

本文介绍了在Spring Boot中如何使用@Async进行异步任务处理,包括启动异步服务、定义异步方法、自定义线程池等,并探讨了@Async失效的几种情况,如未开启异步服务、内部调用、方法权限及非代理对象调用等问题。

@Async 使用和失效情况

因业务需要,经常会遇到主线程中包含其他关联业务,然关联业务的执行结果对主线程的返回结果没有直接影响或无影响。此时,能让主线程更顺畅的执行,并给客户带来好的客户体验,我们一般会将该关联业务做异步处理或类似的处理(如:消息队列),本文记录自己在项目中使用异步服务的相关经历,以备后期查询使用!

一、Springboot 使用异步任务

1、SpringBootApplication启动类添加@EnableAsync注解;

2、@Async使用

(1)类或者方法中使用@Async注解,类上标有该注解表示类中方法都是异步方法,方法上标有该注解表示方法是异步方法;

(2)@Async(“threadPool”),threadPool为自定义线程池,这样可以保证主线程中调用多个异步任务时能更高效的执行。

3、实例、分析

开启异步服务

@SpringBootApplication
@EnableApolloConfig
@EnableAsync
@ComponentScan(basePackages = {"com.zts"})
public class UserMgmtApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserMgmtApplication.class, args);
    }
}

定义异步类或方法:如果异步方法需要返回值,可以用Future接收

@Service
public class TestServiceImpl implements TestCRMService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    @Async("testAsync") // 自定义执行线程池
    public void sendMessage() throws Exception {
        /**
         *  业务实现
         */    
    }

    @Override
    @Async("testAsync") // 自定义执行线程池
    public void sendMail() throws Exception {
        /**
         *  业务实现
         */    
    }

}

调用异步方法

    @Autowired
    TestService testService;
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/test", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(notes = "test()", httpMethod = "GET", value = "测试调用多个异步任务")
    public Map<String,Object> runTaskByKettle( ) throws Exception{
        Map<String,Object> result = new HashMap<>();
        try {
            testService.sendMessage();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("sendMessage任务出现异常");
        }
        try {
            testService.sendMail();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("sendMail任务出现异常");
        }
        return result;
    }

自定义线程池

@Configuration
@EnableAsync
public class ExecutorConfig {

    /** Set the ThreadPoolExecutor's core pool size. */
    private int corePoolSize = 10;
    /** Set the ThreadPoolExecutor's maximum pool size. */
    private int maxPoolSize = 50;
    /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */
    private int queueCapacity = 10;

    @Bean
    public Executor testAsync() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("MgmtExecutor-");

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}

至此,Springboot 调用多个异步任务使用实例完成。

@Async注解 分析

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
    String value() default "";
}

通过查看@Async源码可以看出来,@Target 的值是类和方法,所有异步注解可以作用在方法体上面,也可以作用在类上面。

以上是项目使用,可正常使用,因此验证忽略!

二、Spring boot异步任务@Async失效问题

总结:1、启动类是否开启异步服务;

2、在定义异步方法的同一个类中,调用带有@Async注解方法,该方法则无法异步执行;

3、注解的方法必须是public方法,不能是static;

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

Java使用`@Async`注解实现异步方法调用时,可能会遇到异步方法失效的问题。这种失效通常与Spring AOP代理机制的限制有关,以下是常见导致`@Async`失效的原因及对应的解决方案。 ### 1. 异步方法必须为 `public` 修饰 `@Async`注解的方法必须声明为 `public`,否则Spring AOP将无法为其生成代理,导致异步调用不生效。如果方法被声明为 `protected`、`private` 或者包级私有,则不会触发异步行为[^2]。 ```java @Service public class MyService { @Async public void asyncMethod() { // 异步执行的逻辑 } public void callAsyncMethod() { asyncMethod(); // 正确调用,因为 asyncMethod 是 public 的 } } ``` ### 2. 同类中直接调用异步方法导致失效 在同一个类中,如果一个普通方法直接调用带有`@Async`的方法,由于Spring AOP代理机制的限制,该调用不会经过代理对象,因此异步调用不会生效。解决方法包括: - **方式1:将异步方法拆分到不同类中** 将异步方法定义在另一个服务类中,并通过依赖注入调用,这样可以确保调用是通过代理对象完成的。 - **方式2:通过代理对象调用** 使用`AopContext.currentProxy()`获取当前类的代理对象,再通过代理对象调用异步方法。 ```java @Service public class MyService { @Autowired private MyService selfProxy; @Async public void asyncMethod() { // 异步执行的逻辑 } public void callAsyncMethod() { selfProxy.asyncMethod(); // 通过代理对象调用,确保异步生效 } } ``` ### 3. `final` 方法导致异步失效 如果将`@Async`注解应用于`final`方法上,由于Spring AOP无法对`final`方法进行动态代理(特别是在基于CGLIB的代理机制中),会导致异步调用失效。应避免在`final`方法上使用`@Async`注解[^3]。 ```java @Service public class UserService { public void test() { async("test"); // 调用不会异步执行,因为 async 方法是 final 的 } @Async public void async(String value) { // 应避免使用 final 修饰 // 异步逻辑 } } ``` ### 4. 未正确开启异步支持 确保在配置类或启动类上添加了`@EnableAsync`注解,以启用Spring的异步任务支持。否则,即使使用了`@Async`注解,也不会生效[^4]。 ```java @Configuration @EnableAsync public class AsyncConfig { // 可以在这里自定义线程池等配置 } ``` ### 5. 线程池配置不合理 默认情况下,Spring使用一个简单的线程池来执行异步任务。如果任务量较大或任务执行时间较长,可能导致线程资源耗尽。可以通过自定义线程池来优化异步任务的执行效率。 ```java @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurerSupport { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.setThreadNamePrefix("Async-Executor-"); executor.initialize(); return executor; } } ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值