2.1 Spring boot/cloud 线程池

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";
    }


}

猜你喜欢

转载自blog.csdn.net/ladymorgana/article/details/82997985