SpringBoot 线程池配置和异步任务调用

方式一:重写spring默认线程池的方式

1、相关参数配置

#线程相关配置
#核心线程数
task.pool.corePoolSize: 5
#线程池最大线程数
task.pool.maxPoolSize: 20
#线程最大空闲时间
task.pool.keepAliveSeconds: 300
#队列最大容量
task.pool.queueCapacity: 50
#线程名称前缀
task.pool.threadPrefix: pcv-excutor-

2、重写Spring线程池 配置注入

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    @Autowired
    Environment environment;

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        log.debug("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Integer.parseInt(environment.getProperty("task.pool.corePoolSize"))); //核心线程数
        executor.setMaxPoolSize(Integer.parseInt(environment.getProperty("task.pool.maxPoolSize")));  //最大线程数
        executor.setQueueCapacity(Integer.parseInt(environment.getProperty("task.pool.keepAliveSeconds"))); //队列大小
        executor.setKeepAliveSeconds(Integer.parseInt(environment.getProperty("task.pool.keepAliveSeconds"))); //线程最大空闲时间
        executor.setThreadNamePrefix(environment.getProperty("task.pool.threadPrefix")); ////指定用于新创建的线程名称的前缀。
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}

拓展:线程池拒绝策略

JDK提供了四种拒绝策略
AbortPolicy策略:直接抛出异常
CallerRunsPolicy策略:只用调用者所在线程运行任务
DiscardOldestPolicy策略:丢弃队列中即将执行的任务,并执行当前任务
DiscardPolicy策略:不处理直接丢弃

3、编写任务Task

import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

@Component
@Slf4j
public class AysncTask {

    @Autowired
    DavinciUserService davinciUserService;

    @Async("taskExecutor")
    public Future doCheckDavinciUser(UserInfo userInfo) throws InterruptedException{
        log.info("check davinci user task started.");
        long start = System.currentTimeMillis();
        …
         davinciUserService 执行业务逻辑    
        …

        long end = System.currentTimeMillis();
        log.info("check davinci user task finished, time elapsed: {} ms.", end-start);

        return new AsyncResult<>("check davinci user task accomplished!");
    }
}

4、异步Task 调用

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {


    @Autowired
    AysncTask aysncTask;

    @GetMapping("/index")
    public RequestEntity index (HttpServletRequest request,
                                          HttpServletResponse response){
        try {
            …….
            Future stringFuture = aysncTask.doCheckDavinciUser(userInfo);
            log.info(stringFuture.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 

你可能感兴趣的:(Spring,Boot)