As the system becomes more and more complex, the speed of many interfaces slows down. At this time, it will occur to me that we can use thread pool to handle some time-consuming operations that do not affect the system.

Create a new Spring Boot project

1. ExecutorConfig.xml

New thread pool configuration file.

@Configuration @EnableAsync public class ExecutorConfig { private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class); @Value("${async.executor.thread.core_pool_size}") private int corePoolSize; @Value("${async.executor.thread.max_pool_size}") private int maxPoolSize; @Value("${async.executor.thread.queue_capacity}") private int queueCapacity; @Value("${async.executor.thread.name.prefix}") private String namePrefix; @Bean(name = "asyncServiceExecutor") public Executor asyncServiceExecutor() { logger.info("start asyncServiceExecutor");  ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // Executor.setCorePoolSize (CorePoolSize); // Executor.setMaxPoolSize (maxPoolSize); / / configuration queue size executor. SetQueueCapacity (queueCapacity); / / the name of the configuration of threads in thread pool prefix executor. SetThreadNamePrefix (namePrefix); // Reject-policy: How to deal with a new task when the pool has reached Max size // CALLER_RUNS: Not in the new thread to perform a task, but with the caller's thread to perform the executor. SetRejectedExecutionHandler (new ThreadPoolExecutor. CallerRunsPolicy ()); // Executor.initialize (); // Executor.initialize (); return executor; }}

2. application.yml

The @value configuration is in application.yml, which you can refer to as the configuration

# async: executor: thread # core_pool_size: 10 # max_pool_size: 20 # queue_capacity: # Configure the name of the thread in the thread pool with the name: prefix: async-service-

3. AsyncService.java

Create a Service interface, which is the interface of the asynchronous thread, and simply write the method to its implementation class

Public interface AsyncService {/** */ void executeAsync(); public interface AsyncService {/** */ void executeAsync(); }

4. AsyncServiceImpl.java

Implementation classes that write business logic

@Service public class AsyncServiceImpl implements AsyncService { private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class); @Override @Async("asyncServiceExecutor") public void executeAsync() { logger.info("start executeAsync"); System.out.println(" Asynchronous thread execution has started "); System.out.println(" This is where you can put your time-consuming operations "); logger.info("end executeAsync"); }}

++ Async the Service layer by adding an annotation @Async(” AsyncServiceExecutor “) to the ExecuteAsync () method. The AsyncServiceExecutor method is the name of the method in the previous ExecutorConfig.java, indicating that the thread pool into which the ExecuteAsync method enters is created by the AsyncServiceExecutor method. ++

5. AsyncController.java

Inject the AsyncService into the controller and call one of the methods

@Autowired
private AsyncService asyncService;

@GetMapping("/async")
public void async(){
    asyncService.executeAsync();
}

6. Test with PostMan

Print log in

The 22:15:47 2021-06-16. 10516-655 the INFO [async - service - 5] C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:15:48.655 INFO 10516 -- [async-service-5] -- [async-service-5] c.u.d.e.executor.impl.AsyncServiceImpl : End executeAsync 22:15:47 2021-06-16. 10516-770 the INFO] [async - service - 1 C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:15:47.770 INFO 10516 -- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl : End executeAsync 22:15:47 2021-06-16. 10516-816 the INFO/async - service - 2 C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:15:47.816 INFO 10516 -- [async-service-2] -- [async-service-2] -- [async-service-2] -- [async-service-2] -- [async-service-2] -- [async-service-2] -- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl : End executeAsync 22:15:48 2021-06-16. 10516-833 the INFO [async - service - 3] C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:15:48.834 INFO 10516 -- [async-service-3] [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl : End executeAsync 22:15:48 2021-06-16. 10516-986 the INFO [async - service - 4] C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:15:48.987 INFO 10516 -- [async-service-4] -- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl : end executeAsync

At this point a simple thread pool has been implemented.

5. Print the current thread pool health

5.1 VisiableThreadPoolTaskExecutor. Java

public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor { private static final Logger logger = LoggerFactory.getLogger(VisiableThreadPoolTaskExecutor.class); private void showThreadPoolInfo(String prefix) { ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor(); if (null == threadPoolExecutor) { return; } logger.info("{}, {},taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]", this.getThreadNamePrefix(), prefix, threadPoolExecutor.getTaskCount(), threadPoolExecutor.getCompletedTaskCount(), threadPoolExecutor.getActiveCount(), threadPoolExecutor.getQueue().size()); } @Override public void execute(Runnable task) { showThreadPoolInfo("1. do execute"); super.execute(task); } @Override public void execute(Runnable task, long startTimeout) { showThreadPoolInfo("2. do execute"); super.execute(task, startTimeout); } @Override public Future<? > submit(Runnable task) { showThreadPoolInfo("1. do submit"); return super.submit(task); } @Override public <T> Future<T> submit(Callable<T> task) { showThreadPoolInfo("2. do submit"); return super.submit(task); } @Override public ListenableFuture<? > submitListenable(Runnable task) { showThreadPoolInfo("1. do submitListenable"); return super.submitListenable(task); } @Override public <T> ListenableFuture<T> submitListenable(Callable<T> task) { showThreadPoolInfo("2. do submitListenable"); return super.submitListenable(task); }}

5.2 modify asyncServiceExecutor. Java

Modify the AsyncServiceExecutor method in ExecutorConfig. Java. Change ThreadPoolTaskExecutor Executor = new ThreadPoolTaskExecutor() to ThreadPoolTaskExecutor Executor = new VisiableThreadPoolTaskExecutor()

@Bean(name = "asyncServiceExecutor") public Executor asyncServiceExecutor() { logger.info("start asyncServiceExecutor");  / / modify here ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor (); // Executor.setCorePoolSize (CorePoolSize); // Executor.setMaxPoolSize (maxPoolSize); / / configuration queue size executor. SetQueueCapacity (queueCapacity); / / the name of the configuration of threads in thread pool prefix executor. SetThreadNamePrefix (namePrefix); // Reject-policy: How to deal with a new task when the pool has reached Max size // CALLER_RUNS: Not in the new thread to perform a task, but with the caller's thread to perform the executor. SetRejectedExecutionHandler (new ThreadPoolExecutor. CallerRunsPolicy ()); // Executor.initialize (); // Executor.initialize (); return executor; }

5.3 Use PostMan for testing

The 2021-06-16 22:23:30. 14088-951 the INFO [nio - 8087 - exec - 2] U.D.E.E.I.V isiableThreadPoolTaskExecutor: async-service-, 2. do submit,taskCount [0], completedTaskCount [0], activeCount [0], QueueSize 22:23:30 [0] 2021-06-16. 14088-952 the INFO] [async - service - 1 C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:23:30.953 INFO 14088 -- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl : End executeAsync 22:23:31 2021-06-16. 14088-351 the INFO [nio - 8087 - exec - 3] U.D.E.E.I.V isiableThreadPoolTaskExecutor: async-service-, 2. do submit,taskCount [1], completedTaskCount [1], activeCount [0], QueueSize 22:23:31 [0] 2021-06-16. 14088-353 the INFO/async - service - 2 C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:23:31.353 INFO 14088 -- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl : End executeAsync 22:23:31 2021-06-16. 14088-927 the INFO [nio - 8087 - exec - 5] U.D.E.E.I.V isiableThreadPoolTaskExecutor: async-service-, 2. do submit,taskCount [2], completedTaskCount [2], activeCount [0], QueueSize 22:23:31 [0] 2021-06-16. 14088-929 the INFO [async - service - 3] C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:23:31.930 INFO 14088 -- [async-service-3] [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl : End executeAsync 22:23:32 2021-06-16. 14088-496 the INFO [nio - 8087 - exec - 7] U.D.E.E.I.V isiableThreadPoolTaskExecutor: async-service-, 2. do submit,taskCount [3], completedTaskCount [3], activeCount [0], QueueSize 22:23:32 [0] 2021-06-16. 14088-498 the INFO [async - service - 4] C.U.D.E.E xecutor. Impl. AsyncServiceImpl: 2021-06-16 22:23:32.499 Info 14088 -- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl : end executeAsync

Async-service -, 2. Do submit,taskCount [3], completedTaskCount [3], activeCount [0], queueSize [0]

Personal blog address

http://www.zhouzhaodong.xyz