In the previous blog, http://www.VeVB.COM/article/106718.htm We used the asynchronous operation of spring boot. At that time, we used the default thread pool, but if we wanted to customize our own thread pool according to the project, let’s talk about how to customize the thread pool!
package com.chhliu.springboot.async.configuration; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "spring.task.pool") // The locations of this annotation have been enabled. Now, as long as it is in the environment, public class TaskThreadPoolConfig { private int corePoolSize; private int maxPoolSize; private int keepAliveSeconds; private int queueCapacity; ……… omit getter,setter method……… } package com.chhliu.springboot.async.pool; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import com.chhliu.springboot.async.configuration.TaskThreadPoolConfig; @Configuration @EnableAsync public class TaskExecutePool { @Autowired private TaskThreadPoolConfig config; @Bean public Executor myTaskAsyncPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(config.getCorePoolSize()); executor.setMaxPoolSize(config.getMaxPoolSize()); executor.setQueueCapacity(config.getQueueCapacity()); executor.setKeepAliveSeconds(config.getKeepAliveSeconds()); executor.setThreadNamePrefix("MyExecutor-"); // rejection-policy: How to handle new tasks when the pool has reached max size // CALLER_RUNS: Do not execute tasks in the new thread, but execute executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } } package com.chhliu.springboot.async; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.scheduling.annotation.EnableAsync; import com.chhliu.springboot.async.configuration.TaskThreadPoolConfig; @SpringBootApplication @EnableAsync @EnableConfigurationProperties({TaskThreadPoolConfig.class} ) // Enable configuration properties to support public class SpringbootAsyncApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAsyncApplication.class, args); } } package com.chhliu.springboot.async.pool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component public class AsyncTask { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @Async("myTaskAsyncPool") //myTaskAsyncPool is the method name for configuring the thread pool. If you do not write the method name of the custom thread pool here, the default thread pool will be used public void doTask1(int i) throws InterruptedException{ logger.info("Task"+i+" started."); } } package com.chhliu.springboot.async; import java.util.concurrent.ExecutionException; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.chhliu.springboot.async.pool.AsyncTask; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootAsyncApplicationTests { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private AsyncTask asyncTask; @Test public void AsyncTaskTest() throws InterruptedException, ExecutionException { for (int i = 0; i < 100; i++) { asyncTask.doTask1(i); } logger.info("All tasks finished."); } } The test results are as follows:
2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-10] ccspringboot.async.pool.AsyncTask : Task60 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-25] ccspringboot.async.pool.AsyncTask : Task61 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-6] ccspringboot.async.pool.AsyncTask : Task62 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-23] ccspringboot.async.pool.AsyncTask : Task63 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-20] ccspringboot.async.pool.AsyncTask : Task64 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-19] ccspringboot.async.pool.AsyncTask : Task65 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-16] ccspringboot.async.pool.AsyncTask : Task66 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-15] ccspringboot.async.pool.AsyncTask : Task67 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-15] ccspringboot.async.pool.AsyncTask : Task67 started. 2017-03-20 20:15:15.208 INFO 4068 --- [ MyExecutor-12] ccspringboot.async.pool.AsyncTask : Task68 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-1] ccspringboot.async.pool.AsyncTask : Task69 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-11] ccspringboot.async.pool.AsyncTask : Task81 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-8] ccspringboot.async.pool.AsyncTask : Task82 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-7] ccspringboot.async.pool.AsyncTask : Task83 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-4] ccspringboot.async.pool.AsyncTask : Task84 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-29] ccspringboot.async.pool.AsyncTask : Task85 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-21] ccspringboot.async.pool.AsyncTask : Task86 started. 2017-03-20 20:15:15.209 INFO 4068 --- [ MyExecutor-17] ccspringboot.async.pool.AsyncTask : Task88 started.
Test results are OK!
If we want to use the default thread pool, but just want to modify the configuration of the default thread pool, then what should we do? At this time, we need to implement the AsyncConfigurer class. The sample code is as follows:
import java.lang.reflect.Method; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import com.chhliu.cq.emailservice.threadconfiguration.TaskThreadPoolConfig; import lombok.extern.slf4j.Slf4j; /** * Note: This thread pool is shared by all asynchronous tasks and does not belong to a certain asynchronous task* Description: Thread pool for configuring asynchronous tasks* @author chhliu * Creation time: May 22, 2017 at 10:20:56 am * @version 1.2.0 */ @Slf4j @Configuration public class AsyncTaskExecutePool implements AsyncConfigurer{ @Autowired private TaskThreadPoolConfig config; // To configure the property class, see the above code @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(config.getCorePoolSize()); executor.setMaxPoolSize(config.getMaxPoolSize()); executor.setQueueCapacity(config.getQueueCapacity()); executor.setKeepAliveSeconds(config.getKeepAliveSeconds()); executor.setThreadNamePrefix("taskExecutor-"); // rejection-policy: How to handle new tasks when the pool has reached max size // CALLER_RUNS: The task is not executed in the new thread, but the thread where the caller is located executes executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {// Exception handling in asynchronous tasks return new AsyncUncaughtExceptionHandler() { @Override public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) { log.error("======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================== When using it, just add @Async to the method.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.