springboot任务多种线程池配置详解

线程池配置第一种

import com.esotericsoftware.minlog.Log;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;


import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableScheduling
public class TreadTaskConfig implements SchedulingConfigurer, AsyncConfigurer {

    /** 异步处理 */
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
        TaskScheduler taskScheduler = threadPoolTaskScheduler();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }

SpringUtils.getBean("threadPoolTaskScheduler",TreadConfig.class);

    //线程池维护线程的最少数量
    @Value("${ThreadPoolTask.poolSize}")
    private Integer poolSize;
    //允许的空闲时间
    @Value("${ThreadPoolTask.awaitTerminationSeconds}")
    private Integer awaitTerminationSeconds;
    //线程池名称
    @Value("${ThreadPoolTask.threadNamePrefix}")
    private String threadNamePrefix;
    //缓存队列
    @Value( "${ThreadPoolTask.waitForTasksToCompleteOnShutdown}")
    private Boolean waitForTasksToCompleteOnShutdown;

    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.initialize();
        scheduler.setPoolSize(poolSize);
        scheduler.setThreadNamePrefix(threadNamePrefix);
        scheduler.setAwaitTerminationSeconds(awaitTerminationSeconds);
        scheduler.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        scheduler.setErrorHandler(throwable -> Log.error("调度任务发生异常", throwable));
        return scheduler;

    }

    /** 异步处理 */
    public Executor getAsyncExecutor(){
        Executor executor = threadPoolTaskScheduler();
        return executor;
    }

    /** 异步处理 异常 */
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}

yml里的配置
ThreadPoolTask:
poolSize: 20
awaitTerminationSeconds : 60
threadNamePrefix: PersonTask-Pool-1
waitForTasksToCompleteOnShutdown: true

线程池第二种配置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description:
 * @author: yingjie.zhang
 * @CreateDate:  2019/8/20 11:05
 * */
@ComponentScan
public class ThreadConfig {

    //线程池维护线程的最少数量
    @Value("${ThreaPool.corePoolSize}")
    private Integer corePoolSize;
    //允许的空闲时间
    @Value("${ThreaPool.keepAliveSeconds}")
    private Integer keepAliveSeconds;
    //线程池维护线程的最大数量
    @Value("${ThreaPool.maxPoolSize}")
    private Integer maxPoolSize;
    //缓存队列
   @Value( "${ThreaPool.queueCapacity}")
    private Integer queueCapacity;

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
        executor.setRejectedExecutionHandler(callerRunsPolicy);
        executor.initialize();
        return executor;
    }

}

yml配置
ThreaPool:
corePoolSize: 20
keepAliveSeconds: 200
maxPoolSize: 10
queueCapacity: 20
线程池配置注意注解的使用 注解使用错误也会导致线程池能使用
在需要使用的地方直接注入使用即可
@Autowired
private TaskExecutor taskExecutor;

测试案例

import org.junit.Test;
import org.junit.runner.RunWith;
import org.python.jline.internal.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.core.task.TaskExecutor;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class LoanafterApplicationTests {

    @Autowired
    private TaskExecutor taskExecutor;
    public static <T> List<List<T>> averageAssign(List<T> source,int n){

        List<List<T>> result=new ArrayList<List<T>>();
        //(先计算出余数)
        int remaider=source.size()%n;
        //然后是商
        int number=source.size()/n;
        //偏移量
        int offset=0;
        for(int i=0;i<n;i++){
            List<T> value=null;
            if(remaider>0){
                value=source.subList(i*number+offset, (i+1)*number+offset+1);
                remaider--;
                offset++;
            }else{
                value=source.subList(i*number+offset, (i+1)*number+offset);
            }
            result.add(value);
        }

        return result;

    }

    @Test
    public void contextLoads() {
        List<Integer> integers=new ArrayList<>();
       for (int x=0;x<=1400;x++){
           integers.add(1);
           integers.add(2);
           integers.add(3);
           integers.add(4);
           integers.add(5);
           integers.add(6);
           integers.add(7);
           integers.add(8);
           integers.add(9);
           integers.add(10);
           integers.add(11);
           integers.add(12);
           integers.add(13);
           integers.add(14);
           integers.add(15);
       }

        System.out.println(1);
        List<List<Integer>> lists=averageAssign(integers, 10);
        System.out.println(lists);
        Log.info(lists.size());
        System.out.println(lists.size());
        for (int j = 0; j <lists.size(); j++) {
            List<Integer> lisrrr=lists.get(j);
           if(lisrrr!=null) {
            taskExecutor.execute(new Runnable() {

                    @Override
                    public void run() {

                        System.out.println(lisrrr);
                        System.err.println(Thread.currentThread().getName());
                        System.out.println(System.currentTimeMillis());

//                        try {
//                            threadPoolTaskScheduler.wait(3000);
//
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }

                    }


                });
            }
        }




    }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中使用Druid连接池进行MySQL的线程池配置,你可以按照以下步骤进行操作: 1. 首先,在你的Spring Boot项目的pom.xml文件中添加Druid和MySQL的依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 在application.properties(或application.yml)文件中配置Druid连接池的参数: ```properties # 数据源配置 spring.datasource.url=jdbc:mysql://localhost:3306/db_name spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver # Druid相关配置 spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 spring.datasource.druid.max-wait=60000 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false spring.datasource.druid.pool-prepared-statements=true spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.filters=stat,wall,log4j ``` 3. 创建一个配置类,用于配置Druid数据源: ```java import com.alibaba.druid.pool.DruidDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DruidConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource() { return new DruidDataSource(); } } ``` 4. 在主启动类上加上`@EnableConfigurationProperties(DruidConfig.class)`注解,以启用Druid配置。 现在,你的Spring Boot项目已经配置好了使用Druid连接池进行MySQL的线程池配置。你可以根据实际需求调整Druid的参数,比如连接池的大小、最大等待时间等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值