The thread pool ThreadPoolTaskExecutor used in the project

Create an instance application of the thread pool

package com.youming.shuiku.datacenter.provider.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class AsyncManager {
    
    
    //线程处理类
    private static ThreadPoolTaskExecutor threadPoolTaskExecutor;
    //本类
    private static AsyncManager asyncManager;
    //该无参构造方法用于或得在容器中得线程处理类
    private AsyncManager(){
    
    
        //获得在容器中的线程处理类
        threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(12);//核心线程大小
        threadPoolTaskExecutor.setMaxPoolSize(48 * 2);//最大线程大小
        threadPoolTaskExecutor.setQueueCapacity(500);//队列最大容量
        threadPoolTaskExecutor.setKeepAliveSeconds(300);
        //当提交的任务个数大于QueueCapacity,就需要设置该参数,但spring提供的都不太满足业务场景,可以自定义一个,也可以注意不要超过QueueCapacity即可
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60);
        threadPoolTaskExecutor.setThreadNamePrefix("TaskLogo-Thread-");
        threadPoolTaskExecutor.initialize();
        //查看线程的数量
        if(threadPoolTaskExecutor.getCorePoolSize()!=12){
    
    
            log.info("getMaxPoolSize==="+threadPoolTaskExecutor.getCorePoolSize());
        }
    }
    //该方法用于创建AsyncManager类 就是本类
    public static AsyncManager getInstance(){
    
    
        //判断本类是不是空 如果是空的话就创建一个 返回 如果不是空就直接放回
        if (asyncManager == null){
    
    
            synchronized (AsyncManager.class){
    
    
                if(asyncManager == null){
    
    
                    asyncManager = new AsyncManager();
                    return asyncManager;
                }
            }
        }
        return asyncManager;
    }
    //该方法用于把任务提交
    public void execute(Runnable runnable){
    
    
        //execute线程的无返回值提交方法
        threadPoolTaskExecutor.execute(runnable);
    }
}

use:

AsyncManager.getInstance().execute(asyncFactory.getDingTalkToken());


public Runnable getDingTalkToken() {
    
    
		Runnable runnable = () -> {
    
    
			List<DingTalkConfig> list = dingTalkConfigService.list();
			for (DingTalkConfig dingTalkConfig : list) {
    
    
				String token = acquireDingTalkToken(dingTalkConfig.getCorpId(), dingTalkConfig.getAppSecret());
				redisTemplate.opsForValue().set(dingTalkConfig.getRedisKey(), token, 2, TimeUnit.HOURS);
			}
		};
		return runnable;
	}

Implementing multi-threading using @Async annotation

@EnableAsync is an annotation used to enable asynchronous method execution in the Spring framework. It allows you to use the @Async annotation on methods to implement asynchronous execution of methods. Asynchronous method execution means that when you call these methods, they execute in a separate thread without blocking the main calling thread.

By default, methods in Spring are executed synchronously, that is, method calls wait for the execution of the method to complete before continuing. But sometimes, some methods may need to perform some time-consuming operations. If executed in the main thread, it may cause long response times or affect the throughput of the system. At this time, you can use the @Async annotation and combine it with @EnableAsync to enable asynchronous execution, thereby executing these time-consuming operations in a separate thread to improve system performance and responsiveness.

It should be noted that in order for the @EnableAsync annotation to take effect, you also need to configure an Executor (executor), which is responsible for managing the thread pool of asynchronous methods. Without custom configuration, Spring will use the default thread pool to execute asynchronous methods. You can customize the behavior of the thread pool by implementing the AsyncConfigurer interface on the configuration class or using the @EnableAsync executor attribute.

use:

package com.youming.shuiku.datacenter.provider.config;

import lombok.extern.slf4j.Slf4j;
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.ThreadPoolExecutor;

/**
 * @ fileName:ThreadPoolConfig
 * @ description:
 * @ author:wxh
 * @ createTime:2022/8/13 15:51
 * @
 * version:1.0.0
 */
@Configuration
@EnableAsync
@Slf4j
public class ThreadPoolConfig {
    
    

	@Bean("asyncServiceExecutor")
	public ThreadPoolTaskExecutor asyncServiceExecutor() {
    
    
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// 核心线程数
		executor.setCorePoolSize(4);
		// 最大线程数
		executor.setMaxPoolSize(8);
		// 线程池的队列大小
		executor.setQueueCapacity(1000);
		// 线程名称前缀
		executor.setThreadNamePrefix("async-service-");
		// 当线程池饱和拒绝策略
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		// 初始化
		executor.initialize();
		return executor;
	}

}

When using it, add the corresponding bean name to the method.

Insert image description here
Note: The configuration class needs to be @EnableAsyncannotated to enable multi-threaded execution.

Guess you like

Origin blog.csdn.net/wang121213145/article/details/132017259