栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

Spring Boot项目中@Async注解实现方法的异步调用
    • 1、简介
    • 2、@Async实战
      • 2.1、定义AsyncController.java
      • 2.2、定义AsyncService.java
    • 3、@Async失效问题解决
      • 3.1、原因分析
      • 3.1、解决方式一
      • 3.2、解决方式二
    • 4、自定义异步线程池参数
    • 5、总结

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
 
@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失效问题解决

例如下面的情况:

@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中通过上下文获取自己的代理对象调用异步方法。

@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 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 future = asyncService.getInputStreamFuture("");
ByteFuture byteFuture = future.get();
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/331920.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号