springboot配置线程池,简单配置详解

创建配置类

需要建一个配置类,声明你的线程池得类型配置

这里需要注意,@Bean(name = “threadPoolTaskExecutor”)这个是你声明的线程池的名字,下面用到线程方法,要写这个名字

代码如下:

package com.jingtoo.file.syn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description
 * @ClassName AsyncTaskConfig
 * @Author liuyg
 * @Date 2020/4/21 13:26
 **/
@Configuration
@EnableAsync
public class AsyncTaskConfig implements AsyncConfigurer {

    private Logger logger = LoggerFactory.getLogger(AsyncTaskConfig.class);
    /**
     * ThredPoolTaskExcutor的处理流程 当池子大小小于corePoolSize,就新建线程,并处理请求
     * 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去workQueue中取任务并处理
     * 当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
     * 当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁
     */
    @Override
    @Bean(name = "threadPoolTaskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 最小线程数(核心线程数)
        taskExecutor.setCorePoolSize(300);
        // 最大线程数
        taskExecutor.setMaxPoolSize(400);
        // 等待队列(队列最大长度)
        taskExecutor.setQueueCapacity(1000);
        // 线程池维护线程所允许的空闲时间 ,单位s
        taskExecutor.setKeepAliveSeconds(300);
        // 线程池对拒绝任务(无线程可用)的处理策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        taskExecutor.initialize();
        logger.info("线程池初始化完成...");
        return taskExecutor;
    }

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

    class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            logger.error("Exception occurs in async method", throwable.getMessage());
        }
    }

}

配置线程

一般最好是单独创建一个配置类

注意:

类需要加入两个注解

  • @Component 泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。
  • @EnableAsync启用了 Spring 异步方法执行功能

引入其他service或者类时,需要加入@Lazy注解

@Autowired
@Lazy    //需要加入Lazy注解,不然实体类会报错
private LicenseFtpService licenseFtpService;

完整代码如下:

package com.jingtoo.file.syn;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description
 * @ClassName AsyncTask
 * @Author liuyg
 * @Date 2020/4/21 13:28
 **/
@Component
@EnableAsync
public class AsyncTask {
    private Logger logger = LoggerFactory.getLogger(AsyncTask.class);

    @Autowired
    @Lazy
    private LicenseFtpService licenseFtpService;


    /**
     * @return void
     * @Author liuyg
     * @Description 证照异步复用方法
     * @Date 13:33 2020/4/21
     * @Param [attachment]
     **/
    @Async("threadPoolTaskExecutor")
    public void photoReusing(Attachment attachment) {
        //这里写方法体,具体异步处理方法
    }
}

启动类加入异步线程注解

启动类上也要加入@EnableAsync注解

到这来线程池就配置好了,启动程序,就可以看到线程池初始化成功!

%title插图%num

 

标签

发表评论