SpringBoot中使用线程池

线程池的常规使用:

消息发送类,线程池调用

复制代码
public class MessageClientSendMsg {

    /**
     * 日志记录器
     */
    private static final Log LOGGER = new Log(MessageClientSendMsg.class);

    /**
     * 线程池
     */
    private static ExecutorService threadPool;

    /**
     * trace
     */
    private String trace;

    /**
     * 手机号
     */
    private String cellNum;

    /**
     * 消息实体
     */
    private MessageProducerReq messageProducerReq;

    static {
        threadPool = Executors.newFixedThreadPool(10);//固定个数的线程池
    }

    /**
     * 构造函数
     *
     * @param trace 请求流水
     * @param cellNum 电话号码
     * @param messageProducerReq 消息实体
     */
    public MessageClientSendMsg(String trace, String cellNum, MessageProducerReq messageProducerReq) {

        this.trace = trace;
        this.cellNum = cellNum;
        this.messageProducerReq = messageProducerReq;
    }

    /**
     * 消息发送
     */
    public void sendMsg() {

        SendMsgRunable sendMsgRunable = new SendMsgRunable();

        threadPool.execute(sendMsgRunable);
    }

    /**
     * 发送消息内部类并处理异常,不能影响主线程的业务
     */
    class SendMsgRunable implements Runnable {

        @Override
        public void run() {

            try {
                MessageClientProducer msgClintProducer = new MessageClientProducer();
                msgClintProducer.sendAsyncWithPartition(trace, cellNum, messageProducerReq);
            } catch (Exception e) {
                LOGGER.error("消息发送失败!,trace:" + trace);
            }
        }
    }
}
复制代码

SpringBoot中使用线程池使用@EnableAsync注解和@Async注解

配置线程池:

复制代码
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class BeanConfig {

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("hello-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
复制代码

并发业务:

复制代码
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
public class Test {
    @Async
   public void test(int i){
        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
        try {
            Thread.sleep(10000);
            System.out.println("多线程异步执行"+i+"  "+Thread.currentThread().getName()+"  "+format.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

Controller层使用

复制代码
@GetMapping("/test")
@ResponseBody
public void test(){
    for (int i = 0; i < 100; i++) {
         test.test(i);
    }
}
复制代码

猜你喜欢

转载自www.cnblogs.com/ZenoLiang/p/12624030.html