一、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