Spring Boot项目中@Async注解实现方法的异步调用

本文详细介绍了如何在SpringBoot项目中使用@Async注解实现异步方法调用,包括实战示例、@Async失效问题的原因及解决方案,自定义线程池配置,以及注意事项。重点讲解了异步方法的正确使用和避免常见问题的方法。

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

1、简介

在公司项目的开发过程中,我们常常会遇到以下一些场景:
1、当我们调用第三方接口或者方法的时候,我们不需要等待方法返回才去执行其它逻辑,这时如果响应时间过长,就会极大的影响程序的执行效率。所以这时就需要使用异步方法来并行执行我们的逻辑。
2、在执行IO操作等耗时操作时,因为比较影响客户体验和使用性能,通常情况下我们也可以使用异步方法。
3、类似的应用还有比如发送短信、发送邮件或者消息通知等这些时效性不高的操作都可以适当的使用异步方法。

注意:
  不过异步操作增加了代码的复杂性,所以我们应该谨慎使用,稍有不慎就可能产生意料之外的结果,从而影响程序的整个逻辑。

2、@Async实战

首先在启动类上添加 @EnableAsync 注解。

2.1、定义AsyncController.java

@RestController
@Slf4j
public class AsyncController{

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/doAsync")
    public void doAsync() {
        asyncService.async01();
        asyncService.async02();
        try {
            log.info("start other task...");
            Thread.sleep(1000);
            log.info("other task end...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.2、定义AsyncService.java

 /**
     * @author: dws
     * @date: 2021/9/22 15:07
     * @description: 测试异步方法
  */
@Slf4j
@Service
public class AsyncService{

    @Async
    public void async01() {
        log.info("thread{} start at{}", Thread.currentThread().getName(), System.currentTimeMillis());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("thread{} end at{}", Thread.currentThread().getName(), System.currentTimeMillis());
    }

    @Async
    public void async02() {
        log.info("thread{} start at{}", Thread.currentThread().getName(), System.currentTimeMillis());
        System.out.println(1/0);
        log.info("thread{} end at{}", Thread.currentThread().getName(), System.currentTimeMillis());
    }
}

执行结果:
在这里插入图片描述
通过日志可以看出,方法async01和async02并没有影响后面的代码段执行,即使是方法抛出异常也不会影响其他代码的运行。说明此时,我们成功调用了异步方法。

3、@Async失效问题解决

例如下面的情况:

/**
     * @author: dws
     * @date: 2021/9/22 15:07
     * @description: 测试异步方法
  */
@Slf4j
@Service
public class AsyncService{

	//异步类中直接调用异步方法,@Async会失效
	public void async0() {
		async01();
		async02();
	}

    @Async
    public void async01() {
        log.info("thread{} start at{}", Thread.currentThread().getName(), System.currentTimeMillis());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("thread{} end at{}", Thread.currentThread().getName(), System.currentTimeMillis());
    }

    @Async
    public void async02() {
        log.info("thread{} start at{}", Thread.currentThread().getName(), System.currentTimeMillis());
        System.out.println(1/0);
        log.info("thread{} end at{}", Thread.currentThread().getName(), System.currentTimeMillis());
    }
}
@RestController
@Slf4j
public class AsyncController{

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/doAsync")
    public void doAsync() {
        asyncService.async0();
        try {
            log.info("start other task...");
            Thread.sleep(1000);
            log.info("other task end...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

异步类中直接调用异步方法,@Async会失效。

3.1、原因分析

失效的原因是因为我们是在test()方法中直接调用的async01()和async02()方法,相当于是this.async01()和this.async02()调用的,也就是说真正调用async01()和async02()方法的是AsyncService对象本身调用的,而**@Async和@Transactional**注解本质使用的是动态代理,真正应该是AsyncService的代理对象调用async01()和async02()方法。其实Spring容器在初始化的时候Spring容器会将含有AOP注解的类对象“替换”为代理对象(简单这么理解),那么注解失效的原因就很明显了,就是因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器,那么解决方法也会沿着这个思路来解决。

网上有不少博客说解决方法就是将要异步执行的方法单独抽取成一个类,这样的确可以解决异步注解失效的问题,原理就是当你把执行异步的方法单独抽取成一个类的时候,这个类肯定是被Spring管理的,其他Spring组件需要调用的时候肯定会注入进去,这时候实际上注入进去的就是代理类了,其实还有其他的解决方法,并不一定非要单独抽取成一个类。

3.1、解决方式一

调用异步方法不能与异步方法在同一个类中。例如:《2、实战》那样调用。

3.2、解决方式二

在AsyncService中通过上下文获取自己的代理对象调用异步方法。

/**
     * @author: dws
     * @date: 2021/9/22 15:07
     * @description: 测试异步方法
  */
@Slf4j
@Service
public class AsyncService{
	
	@Autowired
    ApplicationContext context;

	//异步类中直接调用异步方法,@Async会失效
	public void async0() {
	 	AsyncService asyncService = context.getBean(AsyncService.class);
		asyncService.async01();
		asyncService.async02();
	}

    @Async
    public void async01() {
        log.info("thread{} start at{}", Thread.currentThread().getName(), System.currentTimeMillis());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("thread{} end at{}", Thread.currentThread().getName(), System.currentTimeMillis());
    }

    @Async
    public void async02() {
        log.info("thread{} start at{}", Thread.currentThread().getName(), System.currentTimeMillis());
        System.out.println(1/0);
        log.info("thread{} end at{}", Thread.currentThread().getName(), System.currentTimeMillis());
    }
}

4、自定义异步线程池参数

上面的 @Async实战,用的是Spring提供的默认配置,我们可以自定义配置类并实现AsyncConfigurer来自定义@Async线程参数配置。

@Configuration
@EnableAsync
public class AsyncThreadConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        taskExecutor.setCorePoolSize(50);
        // 最大线程数
        taskExecutor.setMaxPoolSize(100);
        // 队列最大长度
        taskExecutor.setQueueCapacity(1000);
        // 线程池维护线程所允许的空闲时间(单位秒)
        taskExecutor.setKeepAliveSeconds(120);
        // 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        taskExecutor.initialize();
        return taskExecutor;
    }

    @Bean
    public Executor getThreadPool() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(100);
        taskExecutor.setMaxPoolSize(150);
        taskExecutor.setQueueCapacity(1000);
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}

5、总结

需要注意:
1、必须在启动类中增加@EnableAsync注解;
2、异步类没有被springboot管理,添加@Component注解(或其他注解)3、且保证可以扫描到异步类;
4、测试异步方法不能与异步方法在同一个类中;
5、测试类中需要使用spring容器初始化的异步类,不能自己手动new对象;

异步方法如果有返回值时,可以使用如下写法:

	@Async
    Future<ByteFuture> getInputStreamFuture(String fileName) {
        ByteFuture byteFuture = new ByteFuture();
        byteFuture.setFileName(fileName);
        try (InputStream inputStream = new URL(fileName.replace(" ", "%20") + "?" + Math.random()).openStream()) {
            log.info("下载文件:{}", fileName);
            byteFuture.setBytes(IOUtils.toByteArray(inputStream));
        } catch (Exception e) {
            log.error("下载文件失败:{}", fileName, e);
        }
        return new AsyncResult<>(byteFuture);
    }

获取异步返回值方式:

Future<ByteFuture> future = asyncService.getInputStreamFuture("");
ByteFuture byteFuture = future.get();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值