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);
    }
}
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM