欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2.1 Spring boot/cloud ​​​​​​​ 线程池

程序员文章站 2022-05-01 13:04:05
...

Step 1:ExecutePool配置,开启@EnableAsync支持异步任务

package com.springboot.begin.threadPool;

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.Executor;
import java.util.concurrent.ThreadPoolExecutor;


@Configuration
@EnableAsync
public class ExecutorPoolConfig {

    private int corePoolSize = 10;
    private int maxPoolSize = 50;
    private int queueSize = 10;
    private int keepAlive = 60;

    @Bean
    public Executor testExecutorPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueSize);
        executor.setKeepAliveSeconds(keepAlive);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.setThreadNamePrefix("TestExecutorPool-");

        executor.initialize();
        return executor;
    }


}

Step 2:执行线程,声明一个异步任务

package com.springboot.begin.threadPool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class ThreadPoolUser {

    @Async("testExecutorPool")
    public void test(){
        String info = "test---" + Thread.currentThread().getName();
        log.info(info);
    }
}

Step 3:测试 (接口调用)

 

package com.springboot.begin;

import com.springboot.begin.threadPool.ThreadPoolUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@Slf4j
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private ThreadPoolUser threadPoolUser;


    @RequestMapping(value = "/threadpool/test" , method=RequestMethod.GET)
    public String threadPoolTest() {
        threadPoolUser.test();
        return "ok";
    }


}