源码分析Elastic-Job前置篇:Spring自定义命名空间原理

本文涉及的产品
注册配置 MSE Nacos/ZooKeeper,182元/月
MSE Nacos/ZooKeeper 企业版试用,1600元额度,限量50份
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: 在 Spring 中使用 Elastic-Job 的示例如下:

在 Spring 中使用 Elastic-Job 的示例如下:

<!--配置作业注册中心 -->
<reg:zookeeper id="regCenter" server-lists="${gis.dubbo.registry.address}"
      namespace="example-job" base-sleep-time-milliseconds="${elasticJob.zkBaseSleepTimeMilliseconds}"
      max-sleep-time-milliseconds="${elasticJob.zkMaxSleepTimeMilliseconds}"
      max-retries="${elasticJob.zkMaxRetries}" />

本文重点剖析如何在 Spring 中自定义命名空间 < reg:zookeeper/>。

1、在META-INF目录下定义xsd文件,Elastic-Job reg.xsd文件定义如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.dangdang.com/schema/ddframe/reg"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:beans="http://www.springframework.org/schema/beans"
        targetNamespace="http://www.dangdang.com/schema/ddframe/reg"
        elementFormDefault="qualified"
        attributeFormDefault="unqualified">
    <xsd:import namespace="http://www.springframework.org/schema/beans"/>
    
    <xsd:element name="zookeeper">
        <xsd:complexType>
            <xsd:complexContent>
                <xsd:extension base="beans:identifiedType">
                    <xsd:attribute name="server-lists" type="xsd:string" use="required" />
                    <xsd:attribute name="namespace" type="xsd:string" use="required" />
                    <xsd:attribute name="base-sleep-time-milliseconds" type="xsd:string" />
                    <xsd:attribute name="max-sleep-time-milliseconds" type="xsd:string" />
                    <xsd:attribute name="max-retries" type="xsd:string" />
                    <xsd:attribute name="session-timeout-milliseconds" type="xsd:string" />
                    <xsd:attribute name="connection-timeout-milliseconds" type="xsd:string" />
                    <xsd:attribute name="digest" type="xsd:string" />
                </xsd:extension>
            </xsd:complexContent>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>
  • xsd:schema元素详解

    • xmlns="http://www.dangdang.com/schema/ddframe/reg":定义默认命名空间。如果元素没有前缀,默认为该命名空间下的元素。
    • xmlns:xsd="http://www.w3.org/2001/XMLSchema",引入xsd命名空间,该命名空间的URL为http://www.w3.org/2001/XMLSchema,元素前缀为xsd。
    • xmlns:beans="http://www.springframework.org/schema/beans",引入Spring beans命名空间.xmlns:xx=""表示引入已存在的命名空间。
    • targetNamespace="http://www.dangdang.com/schema/ddframe/reg":定义该命名空间所对应的url,在xml文件中如果要使用< reg:xx/>,其xsi:schemaLocation定义reg.xsd路径时必须以该值为键,例如应用程序中定义elasticjob的xml文件如下:
    • elementFormDefault="qualified":指定该xsd所对应的实例xml文件,引用该文件中定义的元素必须被命名空间所限定。例如在reg.xsd中定义了zookeeper这个元素,那么在spring-elastic-job.xml(xml文档实例)中使用该元素来定义时,必须这样写: ,而不能写出。
    • attributeFormDefault:指定该xsd所对应的示例xml文件,引用该文件中定义的元素属性是否需要被限定,unqualified表示不需要被限定。如果设置为qualified,则则为错误写法,正确写法如下:

      <reg:zookeeper id="regCenter" reg:server-lists="" .../>。
  • xsd:import
    导入其他命名空间,< xsd:import namespace="http://www.springframework.org/schema/beans"/>

表示导入spirng beans命名空间。如果目标命名空间定义文件没有指定targetNamespace,则需要使用include导入其他命令空间,例如:

<import namespace="tnsB" schemaLocation="B.xsd"> 
  • xsd:zookeeper> 定义zookeeper元素,xml文件中可以使用reg:zookeeper/>。
  • xsd:complexType,zookeeper元素的类型为复杂类型。
  • xsd:extension base="beans:identifiedType">继承beans命名空间identifiedType的属性。(id 定义)。

2、定义NamespaceHandlerSupport实现类。

继承NamespaceHandlerSupport,重写init方法。

public final class RegNamespaceHandler extends NamespaceHandlerSupport {
    
    @Override
    public void init() {
        registerBeanDefinitionParser("zookeeper", new ZookeeperBeanDefinitionParser());
    }
}

注册BeanDefinitionParser解析< reg:zookeeper/>标签,并初始化实例。

ZookeeperBeanDefinitionParser源码:

public final class ZookeeperBeanDefinitionParser extends AbstractBeanDefinitionParser {
    @Override
    protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
        BeanDefinitionBuilder result = BeanDefinitionBuilder.rootBeanDefinition(ZookeeperRegistryCenter.class);// @1
        result.addConstructorArgValue(buildZookeeperConfigurationBeanDefinition(element));  // @2
        result.setInitMethodName("init");   // @3
        return result.getBeanDefinition();  // @4
    }
 //  ....省略部分代码
}

代码@1:构建器模式,表明< reg:zookeeper/>标签对应的实体Bean对象为 ZookeeperRegistryCenter,zk注册中心实现类。
代码@2:最终创建 ZookeeperRegistryCenter,其属性通过构造方法注入。
代码@3:设置 initMethod,相当于配置文件的 init-method 属性,表明在创建实例时将调用该方法进行初始化。
代码@4:返回 AbstractBeanDefinition 对象,方便 Spring 针对该配置创建实例。

ZookeeperBeanDefinitionParser#buildZookeeperConfigurationBeanDefinition

private AbstractBeanDefinition buildZookeeperConfigurationBeanDefinition(final Element element) {
        BeanDefinitionBuilder configuration = BeanDefinitionBuilder.rootBeanDefinition(ZookeeperConfiguration.class);
        configuration.addConstructorArgValue(element.getAttribute("server-lists"));
        configuration.addConstructorArgValue(element.getAttribute("namespace"));
        addPropertyValueIfNotEmpty("base-sleep-time-milliseconds", "baseSleepTimeMilliseconds", element, configuration);
        addPropertyValueIfNotEmpty("max-sleep-time-milliseconds", "maxSleepTimeMilliseconds", element, configuration);
        addPropertyValueIfNotEmpty("max-retries", "maxRetries", element, configuration);
        addPropertyValueIfNotEmpty("session-timeout-milliseconds", "sessionTimeoutMilliseconds", element, configuration);
        addPropertyValueIfNotEmpty("connection-timeout-milliseconds", "connectionTimeoutMilliseconds", element, configuration);
        addPropertyValueIfNotEmpty("digest", "digest", element, configuration);
        return configuration.getBeanDefinition();
    }

根据< reg:zookeeper/>元素,获取 element 的server-lists、namespace 属性,使用ZookeeperConfiguration 构造方式初始化 ZookeeperConfiguration属性,然后解析其他非空属性并使用set 方法注入到 ZookeeperConfiguration 实例。

3、将自定义的 NameSpace、xsd 文件纳入 Spring 的管理范围内。

在 META-INF 目录下创建 spring.handlers、spring.schemas 文件,其内容分别是:

spring.handlers:http\://www.dangdang.com/schema/ddframe/reg=io.elasticjob.lite.spring.reg.handler.RegNamespaceHandler

格式如下:xsd文件中定义的targetNamespace=自定义namespace实现类。

spring.schemas:http\://www.dangdang.com/schema/ddframe/reg/reg.xsd=META-INF/namespace/reg.xsd

格式如下:xsd文件uri = xsd文件目录。

xsi:schemaLocation="http\://www.dangdang.com/schema/ddframe/reg/reg.xsd=META-INF/namespace/reg.xsd"

取的就是该文件的内容。然后元素解析后,然后实例化Bean并调用ZookeeperRegistryCenter的init方法,开始注册中心的启动流程。

下一篇将详细介绍elastic-job注册中心的启动流程。

原文发布时间为:2019-11-28
本文作者:丁威,《RocketMQ技术内幕》作者。
本文来自中间件兴趣圈,了解相关信息可以关注中间件兴趣圈

目录
相关文章
|
2月前
|
缓存 Java 开发者
【Spring】原理:Bean的作用域与生命周期
本文将围绕 Spring Bean 的作用域与生命周期展开深度剖析,系统梳理作用域的类型与应用场景、生命周期的关键阶段与扩展点,并结合实际案例揭示其底层实现原理,为开发者提供从理论到实践的完整指导。
|
2月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
|
人工智能 Java Serverless
【MCP教程系列】搭建基于 Spring AI 的 SSE 模式 MCP 服务并自定义部署至阿里云百炼
本文详细介绍了如何基于Spring AI搭建支持SSE模式的MCP服务,并成功集成至阿里云百炼大模型平台。通过四个步骤实现从零到Agent的构建,包括项目创建、工具开发、服务测试与部署。文章还提供了具体代码示例和操作截图,帮助读者快速上手。最终,将自定义SSE MCP服务集成到百炼平台,完成智能体应用的创建与测试。适合希望了解SSE实时交互及大模型集成的开发者参考。
11603 60
|
30天前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
1月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
318 2
|
2月前
|
监控 安全 Java
使用 @HealthEndpoint 在 Spring Boot 中实现自定义健康检查
Spring Boot 通过 Actuator 模块提供了强大的健康检查功能,帮助开发者快速了解应用程序的运行状态。默认健康检查可检测数据库连接、依赖服务、资源可用性等,但在实际应用中,业务需求和依赖关系各不相同,因此需要实现自定义健康检查来更精确地监控关键组件。本文介绍了如何使用 @HealthEndpoint 注解及实现 HealthIndicator 接口来扩展 Spring Boot 的健康检查功能,从而提升系统的可观测性与稳定性。
196 0
使用 @HealthEndpoint 在 Spring Boot 中实现自定义健康检查
|
3月前
|
Java 关系型数据库 数据库
深度剖析【Spring】事务:万字详解,彻底掌握传播机制与事务原理
在Java开发中,Spring框架通过事务管理机制,帮我们轻松实现了这种“承诺”。它不仅封装了底层复杂的事务控制逻辑(比如手动开启、提交、回滚事务),还提供了灵活的配置方式,让开发者能专注于业务逻辑,而不用纠结于事务细节。
|
7月前
|
存储 人工智能 自然语言处理
RAG 调优指南:Spring AI Alibaba 模块化 RAG 原理与使用
通过遵循以上最佳实践,可以构建一个高效、可靠的 RAG 系统,为用户提供准确和专业的回答。这些实践涵盖了从文档处理到系统配置的各个方面,能够帮助开发者构建更好的 RAG 应用。
3360 114
|
4月前
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
160 0
|
4月前
|
监控 架构师 NoSQL
spring 状态机 的使用 + 原理 + 源码学习 (图解+秒懂+史上最全)
spring 状态机 的使用 + 原理 + 源码学习 (图解+秒懂+史上最全)