Springboot はスレッド プールを迅速に構成します

スレッド プールのアプリケーション シナリオ:

メッセージシステムアラームなどによるメール通知・異常をサービスに埋め込みます。

元のサービスの効率に影響を与える重要でないサービスを最小限に抑え、スレッド プールを使用して非同期に呼び出す必要がある

ステップ:

1. スタートアップ クラスは、アノテーション@EnableAsynを有効にするようにスレッド プールを構成します。

ここに画像の説明を挿入

2. オプション: 構成クラスを構成します (一致しない場合はデフォルトになります)。

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. 非同期である必要があるメソッドに **@Async** アノテーションを使用します。メソッドをプライベートにすることはできません。
構成クラスの構成を使用する場合は、対応する構成の Bean 名を追加します (
例: @Async() 「メールエグゼキュータ」)
ここに画像の説明を挿入


4.スレッドプールの開閉、メール送信内容、メール送信結果などのログの書き込みとログに注意する

おすすめ

転載: blog.csdn.net/weixin_45752941/article/details/112629728