Asynchronous processing using @Async in SpringBoot
Before I begin, I will briefly describe the asynchronous processing
What is asynchronous processing?
It’s good to understand Thread Pool
Simply put, asynchronous is a parallel job processing model
Asynchronous processing does not wait for the job to finish
Process the following tasks as separate threads
It’s like two people doing what an employee was doing
I’m going to write the code now
If you want to use it simply, you can do this
If you want to use it for your project, you can set it up yourself
config/AsyncConfig.java@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport { @Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor =
new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);
executor.setMaxPoolSize(30);
executor.setQueueCapacity(50);
executor.setThreadNamePrefix("Thread-00000");
executor.initialize(); return executor;
}
}
extends AsyncConfiguratorSupport
- setCorePollSize:
By default, the number of threads waiting to run - setMaxPollSize:
Maximum number of threads that can run simultaneously - setQueueCapacity:
If the thread generation request exceeds the maximum,
Save as Queue. Maximum number of Queues - setThreadNamePrefix:
Prefix of thread
Now let’s look at the examples
There are tasks that take 10 seconds to complete
If run this task, Results will be returned in 10 seconds
However, even if the work is in progress, it can be returned immediately
Just add @async on top of class or method
@Async
public class AsyncService {}@Async
public void AsyncTest() {}
Add it wherever you want
I used it in the email transmission part
In fact, I can’t think of any examples…
- Send Email
precautions
- Private method is not available, only public method is available
- Unable to self-invocation, Inner method is not available
- Create a defense code when invoking asynchronous method for QueueCapacity Exceeding Requests
It takes about 5 seconds for an email to be sent
If asynchronous processing is not enabled, users must wait for mail to be sent when sign up
So I used Async here
In this case, regardless of the completion of the mail request, it will be returned immediately after registration in MariaDB
Please let me know if there are any mistakes. Thank you