ThreadPoolTaskExecutor小记

2020-03-11  本文已影响0人  yellow_han

Spring Boot中异步线程池的配置

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
public class AsyncExecutorConfig {

    @Bean
    public Executor asyncServiceExecutor() {
        log.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        //如果是IO密集型应用,则线程池大小设置为2N+1;
        //如果是CPU密集型应用,则线程池大小设置为N+1;
        executor.setCorePoolSize(6);
        //配置最大线程数
        executor.setMaxPoolSize(10);
        //配置队列大小
        executor.setQueueCapacity(10000);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-service-");
        // 设置拒绝策略:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

异步使用方法

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AsyncService {

    @Async("asyncServiceExecutor")
    public Future<String> getAsyncResult1() {
        String result = "asyncResultTest1";
        try {
            Thread.sleep(3000);
            log.info("线程名称:{},睡眠:{}秒", Thread.currentThread().getName(), "3");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<String>(result);
    }

    @Async("asyncServiceExecutor")
    public Future<String> getAsyncResult2() {
        String result = "asyncResultTest2";
        try {
            Thread.sleep(4000);
            log.info("线程名称:{},睡眠:{}秒", Thread.currentThread().getName(), "4");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<String>(result);
    }
}
@RestController
@RequestMapping(value = "/test")
public class TestController extends BaseBeanController {

     //线程池,上面Config中定义的
    @Autowired
    public Executor asyncServiceExecutor;
    @PostMapping(value = "/test")
    public DeferredResult<R> test() throws ExecutionException, InterruptedException {
        DeferredResult deferredResult = new DeferredResult(10000L);
        CompletableFuture<R> result = CompletableFuture.supplyAsync(() -> {
            //耗时方法
        }, asyncServiceExecutor);
        deferredResult.setResult(result.get());
        return deferredResult;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读