In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to use @ Async to create asynchronism in Spring. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
Create an asynchronous method
First, use the IDEA tool to create a Spring-Boot project, and select the dependency package Lombok, with brief steps. Then create the BusyService class and create the busyMethod method, as follows:
@ Service@Slf4jpublic class BusyService {@ Async publicCompletableFuture busyMethod (String name) throws InterruptedException {log.info (name); Strings = "Hello,"+ name+"! "; / / simulate a time-consuming operation, 5 seconds Thread.sleep (5000); returnCompletableFuture.completedFuture (s);}}
The annotation @ Service on BusyService indicates that it will be initialized as an instance by Spring, while @ Slf4j indicates that we can print logs directly using log. Then let's take a look at the busyMethod method, whose return value is that CompletableFuture,CompletableFuture inherits from Future, which combines the results of multiple asynchronous executions into a single asynchronous result, and CompletableFuture is required by any asynchronous service. Let's take a look at the annotation @ Async on the busyMethod method, which is our protagonist today, indicating that the method is asynchronous and is called asynchronously. Looking back at the contents of the method body, we use thread sleep to simulate those time-consuming services and return CompletableFuture.
Executor thread pool
We define a Bean of Executor in the system so that the thread of the executor thread pool is used to execute the asynchronous call. For convenience here, we add this Bean directly to the startup class of Spring-Boot.
@ Beanpublic Executor taskExecutor () {ThreadPoolTaskExecutor executor = newThreadPoolTaskExecutor (); executor.setCorePoolSize (3); executor.setMaxPoolSize (3); executor.setQueueCapacity (500); executor.setThreadNamePrefix ("Java alumni reunion -"); executor.initialize (); returnexecutor;}
We define the maximum number of concurrent threads as 3, and define the maximum number of tasks in the queue as 500. the thread name is prefixed with "Java Alumni". When log prints the log, all threads in the thread pool will print out the thread name of "Java Alumni". Of course, you can also add some other settings. If you do not configure Executor, the Bean,Spring will automatically create a SimpleAsyncTaskExecutor and use it to execute asynchronous methods.
Controller
We use a simple RestController to make the asynchronous call, as follows:
@ 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 jane = busyService.busyMethod ("Jane"); CompletableFuture allen = busyService.busyMethod ("Allen"); CompletableFuture 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 () {. }}
We annotate the startup class with @ EnableAsync so that Spring-Boot can use asynchronous calls. Looking at the test () method, we called the asynchronous methods three times and waited for them to complete before printing them out. We start the project and access this method in the browser at http://localhost:8080/test.
After waiting for 5 seconds, the page returned "success". Let's take a look at the result of background printing:
We see three threads with the name prefix "Java reunion" prefix, printing the log in the busyMethod method. Because the busyMethod method is executed by threads in the executor thread pool that we define. Let's take a look at the log printing time in the test method and the busyMethod method, which shows that CompletableFuture.allOf (jane,allen,james). Join () in the test method has been waiting, waiting for all called asynchronous methods to finish execution before continuing execution.
After reading the above, do you have any further understanding of how to use @ Async to create asynchrony in Spring? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.