Springboot quickly configures the thread pool

Thread pool application scenarios:

Embed mail notifications/abnormalities in the service through message system alarms, etc.

Minimize the unimportant services that affect the efficiency of the original service, and need to use the thread pool to call asynchronously

step:

1. The startup class configures the thread pool to enable the annotation
@EnableAsyn
insert image description here

2. Optional: configure the configuration class (if not matched, it will be the default)

package com.a;

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 java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ExecutorConfig {
    
    

    private int corePoolSize = 10;

    private int maxPoolSize = 200;

    private int queueCapacity = 100;

    public static final String EXECUTORE_COMMON = "commonExecutor";

    public static final String EXECUTOR_MAIL = "mailExecutor";

    @Bean
    public Executor mailExecutor() {
    
     return configExecutor(EXECUTOR_MAIL); }

    @Bean
    public Executor commonExecutor() {
    
    
        return configExecutor("commonExecutor");
    }

    private Executor configExecutor(String threadNamePrefix) {
    
    
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

3. Use the **@Async** annotation on the method that needs to be asynchronous. The method cannot be private.
If you use the configuration of the configuration class, add the bean name of the corresponding configuration,
such as @Async("mailExecutor")
insert image description here

4. Pay attention to log writing
, such as the opening and closing of the thread pool, the content of email sending, the result of email sending, etc. plus logs

Guess you like

Origin blog.csdn.net/weixin_45752941/article/details/112629728