一、進行線程池創建 import cn.hutool.core.thread.ThreadFactoryBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.aop.interceptor.AsyncUncaugh ...
一、進行線程池創建
import cn.hutool.core.thread.ThreadFactoryBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurerSupport; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import java.lang.reflect.Method; import java.util.concurrent.Executor; /** * 線程池配置(非同步線程) */ @Slf4j @Configuration @EnableAsync public class ThreadPoolTaskSchedulerConfig extends AsyncConfigurerSupport { @Bean("threadPoolTaskScheduler") public ThreadPoolTaskScheduler threadPoolTaskScheduler() { //這裡使用的為定時任務線程池,替代@Scheduled註解,進行動態定時任務配置 ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setThreadFactory(ThreadFactoryBuilder.create().build()); scheduler.setPoolSize(60); scheduler.setRemoveOnCancelPolicy(true); scheduler.setThreadNamePrefix("TASK-SCHEDULE-"); scheduler.initialize(); return scheduler; } @Override public Executor getAsyncExecutor() { return threadPoolTaskScheduler(); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (Throwable t, Method m, Object... args) -> { log.error("=============================" + t.getMessage() + "=============================="); log.error("threadPoolTaskScheduler exception Method:" + m.getName()); }; } }
二、創建bean操作對象 提供根據beanName獲取,手動註入bean等方法,適用於不被spring管理的類中(thread、callback)
import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; /** * @author lu_wanli **/ @Component public class SpringHelper implements BeanFactoryPostProcessor, ApplicationContextAware { private static ConfigurableListableBeanFactory beanFactory; /** * 獲取 Spring Bean工廠 * * @return beanFactory */ public static ConfigurableListableBeanFactory getBeanFactory() { return beanFactory; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { SpringHelper.beanFactory = beanFactory; } /** * 獲取指定name的bean */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) throws BeansException { return (T) beanFactory.getBean(name); } /** * 獲取指定type的Bean */ public static <T> T getBean(Class<T> clz) throws BeansException { return beanFactory.getBean(clz); } /** * 包含Bean * * @param name beanClassName * @return true/false */ public static boolean containsBean(String name) { return beanFactory.containsBean(name); } /** * 判斷以給定名字註冊的bean定義是一個singleton還是一個prototype。 如果與給定名字相應的bean定義沒有被找到,將會拋出一個異常(NoSuchBeanDefinitionException) * * @param name beanName * @return boolean */ public static boolean isSingleton(String name) { return beanFactory.isSingleton(name); } private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringHelper.applicationContext = applicationContext; } /** * 動態註入單例bean實例 * * @param beanName bean名稱 * @param singletonObject 單例bean實例 * @return 註入實例 */ public static Object registerSingletonBean(String beanName, Object singletonObject) { //將applicationContext轉換為ConfigurableApplicationContext ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext; //獲取BeanFactory DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory(); //動態註冊bean. defaultListableBeanFactory.registerSingleton(beanName, singletonObject); //獲取動態註冊的bean. return configurableApplicationContext.getBean(beanName); } }
三、創建非同步線程的管理類
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * 非同步任務管理器 * */ public class AsyncManager { /** * 非同步操作任務調度線程池 */ private final ThreadPoolTaskExecutor taskExecutor = SpringHelper.getBean("threadPoolTaskExecutor"); /** * 單例模式 */ private AsyncManager() { } private static final AsyncManager ME = new AsyncManager(); public static AsyncManager me() { return ME; } /** * 執行任務 * * @param task 任務 */ public void execute(Runnable task){ taskExecutor.execute(task); } /** * 停止線程池 */ public void shutdown() { taskExecutor.shutdown(); } }
四、在項目關閉時關閉相關線程池資源
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; /** * 關閉線程池資源 */ @Component public class ShutDownManager { private static final Logger logger = LoggerFactory.getLogger(ShutDownManager.class); @PreDestroy public void destory() { shutdownAsyncManager(); } private void shutdownAsyncManager() { try { logger.info("========關閉任務池=========="); AsyncManager.me().shutdown(); } catch (Exception e) { logger.error(e.getMessage(), e); } } }