美文网首页
执行发布ApplicationEvent事件启动自定义异步线程池

执行发布ApplicationEvent事件启动自定义异步线程池

作者: Depro | 来源:发表于2021-07-31 23:07 被阅读0次
    1. 自定义线程池
      @Bean
      public ThreadPoolTaskExecutor taskExecutor() {
      ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
      taskExecutor.setAllowCoreThreadTimeOut(true);
      taskExecutor.setCorePoolSize(2);
      taskExecutor.setMaxPoolSize(20);
      taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
      taskExecutor.setThreadFactory(new CustomizableThreadFactory("test--springThread-pool-"));
      return taskExecutor;
      }

    自定义spring只默认执行ApplicationEvent的执行器
    @Bean
    public SimpleApplicationEventMulticaster applicationEventMulticaster(ConfigurableListableBeanFactory beanFactory,
    ThreadPoolTaskExecutor taskExecutor) {
    SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(beanFactory);
    multicaster.setTaskExecutor(taskExecutor);
    return multicaster;
    }

    2.原理:
    spring启动中,AbstractApplicationContext#refresh()中,initApplicationEventMulticaster()会初始化一个ApplicationEventMulticaster实例,如果beanFactory容器中能containLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME )
    public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
    就是自定义了ApplicationEventMulticaster,那就用这个 ;如果没有,就spring自己new一个ApplicationEventMulticaster实例this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);,并把单例放到容器中。

    3.执行代码的地方
    applicationContext.publishEvent(event)-->abstractApplicationContext.publisEvent(event)--->getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);---->Executor executor = getTaskExecutor();,这个就是自定义的线程池

    相关文章

      网友评论

          本文标题:执行发布ApplicationEvent事件启动自定义异步线程池

          本文链接:https://www.haomeiwen.com/subject/uhxlvltx.html