SpringBoot自定義線程池

一、SpringBoot自定義線程池最多多少

線程池的大小是由應用程序負責創建的任務決定的。用不太科學的方法來設置線程池的大小,可能會導致應用程序出現各種問題和運行瓶頸。在Springboot中,線程池的大小可能會影響應用程序的吞吐量和可伸縮性。

在Thread類中,在構造函數中提供了一個參數,可以指定線程池最大線程數。該變數名是MAX_THREADS。在Springboot中,我們可以在配置文件中通過設置spring.task.execution.pool.max-threads屬性來設置線程池的大小。

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

  @Override
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(100);
    executor.setQueueCapacity(5);
    executor.setThreadNamePrefix("CustomThreadpoolDemo");
    executor.initialize();
    return executor;
  }
}

二、SpringBoot自定義線程池異常

當線程池出現異常或線程池中的任務執行出現異常時,我們可以使用異常處理程序捕獲和處理異常。

Springboot內置了一個線程池異常處理程序,在發生未捕獲異常時,將自動使用該處理程序。可以為ThreadPoolTaskExecutor指定一個AsyncUncaughtExceptionHandler,以便在發生異常時向處理程序發送信息。

@Configuration
@EnableAsync
public class AsyncConfigWithExceptionHandler implements AsyncConfigurer {

  @Override
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(100);
    executor.setQueueCapacity(5);
    executor.setThreadNamePrefix("CustomThreadpoolDemo");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
  }

  @Override
  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return new CustomAsyncExceptionHandler();
  }
 
  private static class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
      log.error("Exception message - " + ex.getMessage());
      log.error("Method name - " + method.getName());
      for (Object param : params) {
        log.error("Parameter value - " + param);
      }
    }
  }
}

三、SpringBoot自定義線程池無效

在Springboot中,初學者可能會遇到線程池無效的問題。如果在應用程序中配置了線程池,則只有使用@Async注釋的方法才可以在其中運行。設置了線程池時,Springboot會嘗試在其中查詢該注釋的方法,並調用其中方法的副本。

在使用Springboot自定義線程池的方法上添加@Async註解,以使該方法在配置的線程池中運行。如果沒有注入線程池,則可能會調用原始方法。

@Service
public class UserServiceImpl implements UserService{

  @Autowired
  private UserRepository userRepository;

  @Autowired
  private NumberService numberService;

  @Override
  @Async("customAsyncExecutor")
  public CompletableFuture findById(Long id) {
    User user = userRepository.findById(id).orElse(null);
    int randomNumber = numberService.generateRandomNumber();
    user.setRandomNumber(randomNumber);
    return CompletableFuture.completedFuture(user);
  }
}

四、SpringBoot自定義線程池非同步執行

在Springboot中,非同步執行非常常見,並且可以通過簡單地使用@Async註解來實現。使用@Async註解的方法在後台線程池中運行,並立即返回,而不必等待方法返回。

@Service
public class NotificationServiceImpl implements NotificationService {

  @Async("emailSendPool")
  @Override
  public CompletableFuture sendEmailNotification(String email, String message) {
    log.info("Send email to " + email);
    //send email logic
    return CompletableFuture.completedFuture("Email sent successfully to " + email);
  }

  @Async("smsSendPool")
  @Override
  public CompletableFuture sendSmsNotification(String phoneNumber, String message) {
    log.info("Send sms to " + phoneNumber);
    //send sms logic
    return CompletableFuture.completedFuture("SMS sent successfully to " + phoneNumber);
  }
}

五、基於SpringBoot自定義線程池

基於Springboot自定義線程池可以幫助應用程序實現非同步事件處理。除了使用@Async註解外,還可以使用Springboot的基於事件的編程模型來自定義非同步操作。

@Component
public class CartEventListener {

  @Async("cartStateChangePool")
  @EventListener
  public void cartChangeListener(ShoppingCartStateChangedEvent event) {
    //perform cart state change logic
    log.info("Shopping Cart state changed: " + event.getShoppingCart().getState());
  }
}

六、@Async自定義線程池

Springboot的@Async註解可以使用自定義線程池來調用應用程序的非同步方法。使用@Async時,如果未提供自定義執行器,則會使用默認線程池。

@Configuration
@EnableAsync
public class AsyncConfig {

  @Bean("customAsyncExecutor")
  public Executor customAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(100);
    executor.setQueueCapacity(5);
    executor.setThreadNamePrefix("CustomThreadpoolDemo");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
  }
}

七、CompleteFuture自定義線程池

使用CompleteFuture可以幫助我們編寫更清晰,更簡單且更易於擴展的代碼,因為我們可以利用CompleteFuture的方法鏈將片段組合在一起。

@Service
public class OrderServiceImpl implements OrderService {

  @Autowired
  private UserService userService;

  @Autowired
  private ProductService productService;

  @Async("customAsyncExecutor")
  @Override
  public CompletableFuture placeOrder(Long userId, Long productId) {
    CompletableFuture userFuture = userService.findById(userId);
    CompletableFuture productFuture = productService.findById(productId);

    return userFuture.thenCombine(productFuture, (user, product) -> {
        Order order = new Order();
        order.setUser(user);
        order.setProduct(product);
        order.setOrderDate(LocalDateTime.now());
        return order;
    });
  }
}

八、自定義線程池7個參數

在Springboot中,使用ThreadPoolTaskExecutor可以自定義線程池。可以通過以下七個參數設置線程池:

1. corePoolSize:線程池的大小(默認情況下5)

2. maxPoolSize:線程池的最大大小(默認情況下10)

3. queueCapacity:隊列大小(默認情況下100)

4. keepAliveTime:線程池的線程保持活動的時間(默認情況下60s)

5. threadNamePrefix:每個線程的名稱前綴(默認情況下「thread」)

6. rejectedExecutionHandler:拒絕策略(默認情況下使用ThreadPoolExecutor.CallerRunsPolicy)

7. allowCoreThreadTimeout:是否允許核心線程在空閑時間超過keepAliveTime時被回收(默認情況下為false)

@Configuration
@EnableAsync
public class AsyncConfig {

  @Bean("customAsyncExecutor")
  public ThreadPoolTaskExecutor customAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(100);
    executor.setQueueCapacity(5);
    executor.setThreadNamePrefix("CustomThreadpoolDemo");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
  }
}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/296190.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-27 12:58
下一篇 2024-12-27 12:58

相關推薦

  • 從ga角度解讀springboot

    springboot作為目前廣受歡迎的Java開發框架,其中的ga機制在整個開發過程中起著至關重要的作用。 一、ga是什麼 ga即Group Artifacts的縮寫,它是Mave…

    編程 2025-04-29
  • Python中自定義函數必須有return語句

    自定義函數是Python中最常見、最基本也是最重要的語句之一。在Python中,自定義函數必須有明確的返回值,即必須要有return語句。本篇文章將從以下幾個方面對此進行詳細闡述。…

    編程 2025-04-29
  • Python線程等待指南

    本文將從多個方面詳細講解Python線程等待的相關知識。 一、等待線程結束 在多線程編程中,經常需要等待線程執行完畢再進行下一步操作。可以使用join()方法實現等待線程執行完畢再…

    編程 2025-04-29
  • Python兩個線程交替列印1到100

    這篇文章的主題是關於Python多線程的應用。我們將會通過實際的代碼,學習如何使用Python兩個線程交替列印1到100。 一、創建線程 在Python中,我們可以使用Thread…

    編程 2025-04-28
  • ROS線程發布消息異常解決方法

    針對ROS線程發布消息異常問題,我們可以從以下幾個方面進行分析和解決。 一、檢查ROS代碼是否正確 首先,我們需要檢查ROS代碼是否正確。可能會出現的問題包括: 是否正確初始化RO…

    編程 2025-04-28
  • Python自定義列表

    本文將為大家介紹Python中自定義列表的方法和應用場景。對自定義列表進行詳細的闡述,包括列表的基本操作、切片、列表推導式、列表的嵌套以及列表的排序,希望能夠幫助大家更好地理解和應…

    編程 2025-04-27
  • Python線程池並發爬蟲

    Python線程池並發爬蟲是實現多線程爬取數據的常用技術之一,可以在一定程度上提高爬取效率和數據處理能力。本文將從多個方面對Python線程池並發爬蟲做詳細的闡述,包括線程池的實現…

    編程 2025-04-27
  • 如何添加Python自定義模塊?

    Python是一種非常流行的腳本語言,因其易學易用和功能強大而備受歡迎。自定義模塊是Python開發中經常使用的功能之一。本文將從多個方面為您介紹如何添加Python自定義模塊。 …

    編程 2025-04-27
  • SpringBoot Get方式請求傳參用法介紹

    本文將從以下多個方面對SpringBoot Get方式請求傳參做詳細的闡述,包括URL傳參、路徑傳參、請求頭傳參、請求體傳參等,幫助讀者更加深入地了解Get請求方式下傳參的相關知識…

    編程 2025-04-27
  • SpringBoot如何設置不輸出Info日誌

    本篇文章將帶您了解如何在SpringBoot項目中關閉Info級別日誌輸出。 一、為什麼要關閉Info日誌 在開發中,我們經常會使用Log4j、Logback等框架來輸出日誌信息,…

    編程 2025-04-27

發表回復

登錄後才能評論