温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring中怎么利用@Async创建异步

发布时间:2021-07-30 16:33:00 来源:亿速云 阅读:189 作者:Leah 栏目:大数据

今天就跟大家聊聊有关Spring中怎么利用@Async创建异步,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

创建异步方法

首先,使用IDEA工具创建Spring-Boot项目,并且选择依赖包Lombok,具体步骤略。然后创建BusyService类,并创建busyMethod方法,具体如下:

@Service@Slf4jpublic class BusyService {  @Async  publicCompletableFuture<String> busyMethod(String name)       throws InterruptedException {    log.info(name);    Strings = "Hello,"+name+"!";    //模拟耗时操作,5秒    Thread.sleep(5000);    returnCompletableFuture.completedFuture(s);  }}

其中,BusyService上的注解@Service标识着它会被Spring初始化为一个实例,而@Slf4j则标识着我们可以直接使用log打印日志。然后我们再看看busyMethod方法,它的返回值是CompletableFuture,CompletableFuture继承自Future,它可以把多个异步执行的结果合并到一个单独的异步结果中,CompletableFuture是任何异步服务所需要的。我们再看看busyMethod方法上的注解@Async,这个注解是我们今天的主角,它标识着这个方法是异步方法,调用它时是异步调用的。再看看方法体中的内容,我们使用了线程休眠模拟那些耗时的服务,并返回CompletableFuture。  

Executor线程池

我们在系统定义一个Executor的Bean,使得异步调用时,使用Executor线程池的线程去执行。这里为了方便,我们直接在Spring-Boot的启动类中增加这个Bean。

@Beanpublic Executor taskExecutor() {  ThreadPoolTaskExecutor executor = newThreadPoolTaskExecutor();  executor.setCorePoolSize(3);  executor.setMaxPoolSize(3);  executor.setQueueCapacity(500);  executor.setThreadNamePrefix("Java同学会-");  executor.initialize();  returnexecutor;}

  

我们定义了最大的并发线程数为3,并且定义了队列中的最大任务数为500,线程名字的前缀为“Java同学会”,在log打印日志时,凡是线程池中的线程执行的,都会打印出“Java同学会”的线程名字。当然你还可以增加一些其他的设置。如果你不配置Executor这个Bean,Spring会自动创建SimpleAsyncTaskExecutor,并使用它来执行异步方法。

Controller

我们使用一个简单的RestController完成异步的调用,如下所示:

@SpringBootApplication@RestController@EnableAsync@Slf4jpublic class SpringAsyncApplication {  @Autowired  privateBusyService busyService;  publicstatic void main(String[] args) {    SpringApplication.run(SpringAsyncApplication.class, args);  }  @RequestMapping("test")  publicString test() throws InterruptedException, ExecutionException {    CompletableFuture<String> jane = busyService.busyMethod("Jane");    CompletableFuture<String> allen = busyService.busyMethod("Allen");    CompletableFuture<String> james = busyService.busyMethod("James");    CompletableFuture.allOf(jane,allen,james).join();    log.info(jane.get());    log.info(allen.get());    log.info(james.get());    return"success";  }  @Bean  publicExecutor taskExecutor() {    ……  }}

  

我们在启动类上加上@EnableAsync注解,使得Spring-Boot可以使用异步调用。再看看test()方法,我们调用了3次异步方法,并等待它们全部完成后,将它们打印出来。我们启动项目,并在浏览器中访问这个方法,地址是:http://localhost:8080/test。

Spring中怎么利用@Async创建异步

我们在等待了5秒后,页面上返回了“success”。我们再看看后台打印的结果:

Spring中怎么利用@Async创建异步

 我们看到名字前缀为“Java同学会”前缀的3个线程,打印了busyMethod方法中的日志。因为busyMethod方法是我们定义的Executor线程池中的线程执行的。我们再看看test方法和busyMethod方法中日志打印的时间,它们相隔了5秒,说明test方法中的CompletableFuture.allOf(jane,allen,james).join()一直在等待,等待所有调用的异步方法都执行完,才继续执行。

看完上述内容,你们对Spring中怎么利用@Async创建异步有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI