首页 > 其他分享 >spring boot 自定义线程池与使用

spring boot 自定义线程池与使用

时间:2022-10-03 11:13:59浏览次数:58  
标签:return 自定义 spring springframework 线程 import org public

一、进行线程池创建

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);
        }
    }

}

 

标签:return,自定义,spring,springframework,线程,import,org,public
From: https://www.cnblogs.com/Sora-L/p/16750136.html

相关文章

  • SpringBoot--解决子线程无法获得HttpServletRequest的attribute的问题
    ​简介    本文介绍解决SpringBoot子线程无法获得HttpServletRequest的attribute的问题。    在SpringBoot请求中,如果创建了子线程获取request的attribute,......
  • SpringBoot--手动校验@NotBlank、@NotNull等的工具类
    ​简介说明        本文介绍手动校验@NotBlank、@NotNull等的工具类。    使用场景:controller接口的入参很多,需要他人提供,但他人提供的类的字段很多,字段都......
  • SpringBoot--解决@Transactional与@CacheEvict联合使用导致的缓存与数据库的一致性问
    ​简介说明    本文介绍@Transactional与@CacheEvict联合使用导致的缓存与数据库的一致性问题的原因及解决方案。注解的作用        @Transactional:给当前......
  • 一篇文章带你掌握主流基础框架——Spring
    一篇文章带你掌握主流基础框架——Spring这篇文章中我们将会介绍Spring的框架以及本体内容,包括核心容器,注解开发,AOP以及事务等内容那么简单说明一下Spring的必要性:Spri......
  • 自定义注解
    转载:http://www.qizhentao.cn/article/15#menu_7https://www.bilibili.com/video/BV1Ma411u7SD?p=1&vd_source=46d50b5d646b50dcb2a208d3946b1598......
  • 写过自定义指令吗,原理是什么?
    背景看了一些自定义指令的文章,但是探究其原理的文章却不多见,所以我决定水一篇。如何自定义指令?其实关于这个问题官方文档上已经有了很好的示例的,我们先来温故一下。除......
  • 10-Elasticsearch-SpringBoot整合ES集群
    SpringBoot整合Elasticsearch集群每个版本的整合方式不一样,具体的使用的时候,直接去找官网的文档就好为什么这个说呢,因为我看之前的版本用的直接是RightHigh的客户......
  • SpringBoot整合Redis[哨兵版]
    SpringBoot整合Redis[哨兵版]修改配置文件server:port:8080spring:application:name:redisredis:#host:192.168.247.141#port:6379......
  • Redis的线程模型
      我觉得这个图就非常清晰,如果是懂BIO/Netty的人看起来应该很容易,是的没错Redis的线程模型就是基于多路复用器做的,采用非阻塞的IO模型,当前是6.x之前的版本,6.......
  • SpringBoot整合Redis[单机版]
    SpringBoot整合Redis[单机版]添加依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>......