首页 > 其他分享 >springboot定时任务线程池配置拾遗--利用配置类进行配置

springboot定时任务线程池配置拾遗--利用配置类进行配置

时间:2023-11-23 21:14:36浏览次数:35  
标签:builder springboot -- TaskSchedulingProperties 配置 public 线程 class

springboot定时任务线程池配置拾遗--利用配置类进行配置

目录

1 springboot自动装配

自从上次简单了解了spring中schedule的线程池配置之后,我又去粗略学习了一下相关的源码,梳理了一下springboot是如何装配线程池的。

1.1 通过TaskSchedulingProperties获取yaml参数

TaskSchedulingProperties是一个schedule的配置类,它通过@ConfigurationProperties("spring.task.scheduling")注解注入yaml配置文件中schedule相关的配置。如果我们没有做配置,它默认线程名称为“scheduling”,线程容量是1,不开启优雅关机。所以默认情况下定时任务是单线程异步的。来看一下源码:

@ConfigurationProperties("spring.task.scheduling")
public class TaskSchedulingProperties {
    private final TaskSchedulingProperties.Pool pool = new TaskSchedulingProperties.Pool();
    private final TaskSchedulingProperties.Shutdown shutdown = new TaskSchedulingProperties.Shutdown();
    private String threadNamePrefix = "scheduling-";

    public TaskSchedulingProperties() {
    }

    public TaskSchedulingProperties.Pool getPool() {
        return this.pool;
    }

    public TaskSchedulingProperties.Shutdown getShutdown() {
        return this.shutdown;
    }

    public String getThreadNamePrefix() {
        return this.threadNamePrefix;
    }

    public void setThreadNamePrefix(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
    }

    public static class Shutdown {
        private boolean awaitTermination;
        private Duration awaitTerminationPeriod;

        public Shutdown() {
        }

        public boolean isAwaitTermination() {
            return this.awaitTermination;
        }

        public void setAwaitTermination(boolean awaitTermination) {
            this.awaitTermination = awaitTermination;
        }

        public Duration getAwaitTerminationPeriod() {
            return this.awaitTerminationPeriod;
        }

        public void setAwaitTerminationPeriod(Duration awaitTerminationPeriod) {
            this.awaitTerminationPeriod = awaitTerminationPeriod;
        }
    }

    public static class Pool {
        private int size = 1;

        public Pool() {
        }

        public int getSize() {
            return this.size;
        }

        public void setSize(int size) {
            this.size = size;
        }
    }
}

1.2 TaskSchedulingAutoConfiguration自动配置类根据TaskSchedulingProperties的配置装配线程池

TaskSchedulingAutoConfiguration是一个springboot的自动配置类,会读取TaskSchedulingProperties中的配置参数。当存在定时任务相关BBP的同时不存在定时任务管理器相关的Bean时,它就会根据参数自动配置一个定时任务线程池。看一下源码:

@ConditionalOnClass({ThreadPoolTaskScheduler.class})
@AutoConfiguration(
    after = {TaskExecutionAutoConfiguration.class}
)
@EnableConfigurationProperties({TaskSchedulingProperties.class})
public class TaskSchedulingAutoConfiguration {
    public TaskSchedulingAutoConfiguration() {
    }

    @Bean
    @ConditionalOnBean(
        name = {"org.springframework.context.annotation.internalScheduledAnnotationProcessor"}
    )
    @ConditionalOnMissingBean({SchedulingConfigurer.class, TaskScheduler.class, ScheduledExecutorService.class})
    public ThreadPoolTaskScheduler taskScheduler(TaskSchedulerBuilder builder) {
        return builder.build();
    }

    @Bean
    @ConditionalOnBean(
        name = {"org.springframework.context.annotation.internalScheduledAnnotationProcessor"}
    )
    public static LazyInitializationExcludeFilter scheduledBeanLazyInitializationExcludeFilter() {
        return new ScheduledBeanLazyInitializationExcludeFilter();
    }

    @Bean
    @ConditionalOnMissingBean
    public TaskSchedulerBuilder taskSchedulerBuilder(TaskSchedulingProperties properties, ObjectProvider<TaskSchedulerCustomizer> taskSchedulerCustomizers) {
        TaskSchedulerBuilder builder = new TaskSchedulerBuilder();
        builder = builder.poolSize(properties.getPool().getSize());
        Shutdown shutdown = properties.getShutdown();
        builder = builder.awaitTermination(shutdown.isAwaitTermination());
        builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
        builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
        builder = builder.customizers(taskSchedulerCustomizers);
        return builder;
    }
}

2 配置类线程池配置方式

从源码里可以看到,自动装配线程池的一个条件是不存在{SchedulingConfigurer.class, TaskScheduler.class, ScheduledExecutorService.class}的Bean。所以我们应该也可以主动配置一个线程池Bean,并且这种情况下将会覆盖yaml配置的参数。下面我就创建一个定时任务线程池的配置类进行测试:

@Configuration
public class ScheduleConfig {

    @Bean
    public ThreadPoolTaskScheduler configScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(2);
        scheduler.setThreadNamePrefix("nagiumi-config-scheduler-");
        return scheduler;
    }
}

再次启动项目,输出内容如下:

nagiumi-config-scheduler-1------run1···Thu Nov 23 20:53:42 CST 2023
nagiumi-config-scheduler-1------run1···Thu Nov 23 20:53:43 CST 2023
nagiumi-config-scheduler-1------run1···Thu Nov 23 20:53:44 CST 2023
nagiumi-config-scheduler-1------run1···Thu Nov 23 20:53:45 CST 2023
nagiumi-config-scheduler-2------run2···Thu Nov 23 20:53:45 CST 2023
nagiumi-config-scheduler-1------run1···Thu Nov 23 20:53:46 CST 2023

可以看到定时任务可以实现多线程同步进行,并且确实覆盖了yaml配置的参数。

标签:builder,springboot,--,TaskSchedulingProperties,配置,public,线程,class
From: https://www.cnblogs.com/nagiumi-misaka/p/17852496.html

相关文章

  • 11.23每日总结
    /AbstractChatroom.javapackageorg.example.test017;importjavax.swing.plaf.basic.BasicTreeUI;publicabstractclassAbstractChatroom{publicabstractvoidregister(Membermember);publicabstractvoidsendText(Stringfrom,Stringto,Stringme......
  • [Docker] Mac M2 – no such file or directory: /var/lib/docker/volumes ,找不到var/
    MacM2ProDocker24.0.6$dockervolumeinspect14dfdb65fb7075d91b2004c979a3591df54bcc1303ff3ca96a3536f4761a19cc[{"CreatedAt":"2023-11-21T12:52:27Z","Driver":"local","Labels......
  • Playwright爬虫绕过Cloudflare人机验证
    1.问题描述有些网关接入了Cloudflare的人机验证组件,当使用Playwright等自动化工具爬取的时候,会被人机验证阻拦。阻断的效果如下:2.问题原因Selenium、Puppeteer、Playwright等自动化控制工具的实现都会遵循一个规范,就是使用这些工具的时候,获取navigator的webdriver属性时......
  • tls 握手时被公司路由器网关阻断
    经过一天的研究发现当tcp三次握手成功后,客户端向服务端发送clienthello包时被网络出口网关设备立即返回RST包。客户端日志立即打印如下:随即tls建立连接失败。[2023-11-2317:47:55][ERROR]127.0.0.1:59998SSLhandshakefailedwithigcc.cc:9120:Connectionresetbypeer......
  • find/filter的区域
    我们在处理数据的时候,经常是返一个list,然后在里面查找,比如根据id来。 letfefines=list.find((item)=>item.id==fineId.value);这个fefines返回的是个对象。 letfefines=list.filter((item)=>{returnitem.id==fineId.value});这个fefines是个数组......
  • go--条件判断 if、switch
    if基本语法if条件A{...}elseif条件B{...}elseif条件C{...}else{...}例子packagemainimport"fmt"funcmain(){varfruitstring="6个苹果"varwatermelonbool=falseifwatermelon{//watermelon为true时,执行......
  • Cookie session
    今日概要【零】发展史一开始:只有一个页面,没有登录功能,大家看到东西都一样新闻时代发展,出现了需要登录注册的网站,要有一门技术存储我们的登录信息京东、天猫cookie存储形式:k:v键值对存储位置:客户端不安全,信息可能会泄露时代发展,需要有一门新的安全的技术sess......
  • FB自动发帖机器人
    探索FB自动发帖机器人:便利与潜在风险 在当今社交媒体时代,Facebook(FB)作为全球最大的社交网络平台之一,已经成为人们分享信息、交流观点和建立社交关系的重要场所。随着人工智能技术的不断发展和应用,FB自动发帖机器人应运而生,它们可以根据预设的规则或算法自动发布内容,为用户节省......
  • 模板语法之句点符的深度查询
     views.py:defindex(request):num=10ss='lqzishandsome'b=Falsell=[1,2,43,{'name':'egon'}]dic={'name':'lqz','age':18}deftest():print('我是tes......
  • cbv本质 前后端交互编码方式
    #1请来了,路由匹配成功执行path('index/',views.Index.as_view()), 执行views.Index.as_view()()#2本质是执行as_view()内部有个闭包函数view()#3本质是view()---》dispatch()#4dispatch内部,根据请求的方法(get,post)---->执行视图类中的defgetdefpost     ......