Dubbo-自定义标签
1、Dubbo的一些自定义标签
<!-- 提供方应用信息,用于计算依赖关系 --> <dubbo:application name="uop" owner="uce"/> <!-- 使用zookeeper注册中心暴露服务地址 --> <dubbo:registry protocol="zookeeper" address="zookeeper://192.168.xx.xx:2181?backup=192.168.xx.xx:2182,192.168.xx.xx:2183" /> <!--dubbox中引入Kryo和FST这两种高效Java序列化实现,来逐步取代原生dubbo中的hessian2,如果使用kryo记得添加依赖 --> <dubbo:protocol name="dubbo" serialization="kryo" port="20990" /> <!-- 定义服务提供者默认属性值 --> <dubbo:provider timeout="5000" threadpool="fixed" threads="100" accepts="1000" token="true"/> <!-- 暴露服务接口 一个服务可以用多个协议暴露,一个服务也可以注册到多个注册中心--> <!--Provider上尽量多配置Consumer端的属性,让Provider实现者一开始就思考Provider服务特点、服务质量的问题--> <dubbo:service interface="com.yingjun.dubbox.api.UserService" ref="userService" />
2、Spring自定义标签即命令空间实现
dubbo自定义标签与命名空间其实现代码在模块dubbo-config中
2.1、DubboNamespaceHandler
public class DubboNamespaceHandler extends NamespaceHandlerSupport implements ConfigurableSourceBeanMetadataElement {
@Override
public void init() {
registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
registerBeanDefinitionParser("config-center", new DubboBeanDefinitionParser(ConfigCenterBean.class, true));
registerBeanDefinitionParser("metadata-report", new DubboBeanDefinitionParser(MetadataReportConfig.class, true));
registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
registerBeanDefinitionParser("metrics", new DubboBeanDefinitionParser(MetricsConfig.class, true));
registerBeanDefinitionParser("ssl", new DubboBeanDefinitionParser(SslConfig.class, true));
registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
registerBeanDefinitionParser("annotation", new AnnotationBeanDefinitionParser());
}
}
2.2、定义dubbo.xsd 文件
在dubbo-config-spring模块下的 src/main/resouce/META-INF中分别定义dubbo.xsd、spring.handlers、spring.schemas
3、Bean解析机制
DubboBeanDefinitionParser
public class DubboBeanDefinitionParser implements BeanDefinitionParser {
private static final Logger logger = LoggerFactory.getLogger(DubboBeanDefinitionParser.class);
private static final Pattern GROUP_AND_VERSION = Pattern.compile("^[\\-.0-9_a-zA-Z]+(\\:[\\-.0-9_a-zA-Z]+)?$");
private static final String ONRETURN = "onreturn";
private static final String ONTHROW = "onthrow";
private static final String ONINVOKE = "oninvoke";
private static final String METHOD = "Method";
private final Class<?> beanClass;
// 该标签的ID是否必须
private final boolean required;
public DubboBeanDefinitionParser(Class<?> beanClass, boolean required) {
this.beanClass = beanClass;
this.required = required;
}
@SuppressWarnings("unchecked")
private static RootBeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
// 创建BeanBeanDefinition对象
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setBeanClass(beanClass);
beanDefinition.setLazyInit(false);
// 解析id属性
String id = resolveAttribute(element, "id", parserContext);
// 如果id属性为空且required为true
if (StringUtils.isEmpty(id) && required) {
// 解析name属性
String generatedBeanName = resolveAttribute(element, "name", parserContext);
// 如果name属性为空
if (StringUtils.isEmpty(generatedBeanName)) {
// 如果是ProtocolConfig置name为dubbo
if (ProtocolConfig.class.equals(beanClass)) {
generatedBeanName = "dubbo";
} else {
// 解析interface属性
generatedBeanName = resolveAttribute(element, "interface", parserContext);
}
}
// 如果name属性仍为空
if (StringUtils.isEmpty(generatedBeanName)) {
// 置name为beanClass的全类名
generatedBeanName = beanClass.getName();
}
// 置id为name
id = generatedBeanName;
// 如果id已存在,则为 name + 序号,例如 name,name2,name3
int counter = 2;
while (parserContext.getRegistry().containsBeanDefinition(id)) {
id = generatedBeanName + (counter++);
}
}
// 如果id不为空
if (StringUtils.isNotEmpty(id)) {
// 如果id已存在则抛异常
if (parserContext.getRegistry().containsBeanDefinition(id)) {
throw new IllegalStateException("Duplicate spring bean id " + id);
}
// 将<id, beanDefinition>注册到Spring容器中
parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
// beanDefinition添加id属性值
beanDefinition.getPropertyValues().addPropertyValue("id", id);
}
/**
* 为ServiceBean设置protocol属性值
*
* <dubbo:protocol name="dubbo" serialization="kryo" port="20990" />
* <dubbo:service protocol="dubbo" interface="com.yingjun.dubbox.api.UserService" ref="userService" />
*/
// 如果beanClass是ProtocolConfig
if (ProtocolConfig.class.equals(beanClass)) {
// 遍历所有的BeanDefinition
for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
// 获得BeanDefinition的protocol属性值
PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
// 如果BeanDefinition的protocol属性值不为空
if (property != null) {
Object value = property.getValue();
// 如果value是ProtocolConfig类型且id等于value的name属性值
if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) {
// BeanDefinition添加protocol属性值类型为RuntimeBeanReference
definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id));
}
}
}
// 如果beanClass是ServiceBean
} else if (ServiceBean.class.equals(beanClass)) {
// 解析class属性
String className = resolveAttribute(element, "class", parserContext);
if (StringUtils.isNotEmpty(className)) {
RootBeanDefinition classDefinition = new RootBeanDefinition();
// 反射获得Class对象
classDefinition.setBeanClass(ReflectUtils.forName(className));
classDefinition.setLazyInit(false);
// 解析子标签
parseProperties(element.getChildNodes(), classDefinition, parserContext);
// BeanDefinition添加ref属性值
beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
}
}
// 如果beanClass是ProviderConfig
else if (ProviderConfig.class.equals(beanClass)) {
parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", id, beanDefinition);
}
// 如果beanClass是ProviderConfig
else if (ConsumerConfig.class.equals(beanClass)) {
parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition);
}
Set<String> props = new HashSet<>();
ManagedMap parameters = null;
// 获得beanClass所有的方法
for (Method setter : beanClass.getMethods()) {
String name = setter.getName();
// 过滤set方法
if (name.length() > 3 && name.startsWith("set")
&& Modifier.isPublic(setter.getModifiers())
&& setter.getParameterTypes().length == 1) {
Class<?> type = setter.getParameterTypes()[0];
String beanProperty = name.substring(3, 4).toLowerCase() + name.substring(4);
// 驼峰转连接,sayHello -> say-hello
String property = StringUtils.camelToSplitName(beanProperty, "-");
props.add(property);
// check the setter/getter whether match
Method getter = null;
try {
getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
} catch (NoSuchMethodException e) {
try {
getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
} catch (NoSuchMethodException e2) {
// ignore, there is no need any log here since some class implement the interface: EnvironmentAware,
// ApplicationAware, etc. They only have setter method, otherwise will cause the error log during application start up.
}
}
if (getter == null
|| !Modifier.isPublic(getter.getModifiers())
|| !type.equals(getter.getReturnType())) {
continue;
}
if ("parameters".equals(property)) {
// 解析<dubbo:parameter key="" value="" />标签
parameters = parseParameters(element.getChildNodes(), beanDefinition, parserContext);
} else if ("methods".equals(property)) {
// 解析<dubbo:method />标签
parseMethods(id, element.getChildNodes(), beanDefinition, parserContext);
} else if ("arguments".equals(property)) {
// 解析<dubbo:argument index="0" type="java.lang.String" />标签
parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
} else {
String value = resolveAttribute(element, property, parserContext);
if (value != null) {
value = value.trim();
if (value.length() > 0) {
// 如果服务不注册
if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
beanDefinition.getPropertyValues().addPropertyValue(beanProperty, registryConfig);
} else if ("provider".equals(property) || "registry".equals(property) || ("protocol".equals(property) && AbstractServiceConfig.class.isAssignableFrom(beanClass))) {
/**
* For 'provider' 'protocol' 'registry', keep literal value (should be id/name) and set the value to 'registryIds' 'providerIds' protocolIds'
* The following process should make sure each id refers to the corresponding instance, here's how to find the instance for different use cases:
* 1. Spring, check existing bean by id, see{@link ServiceBean#afterPropertiesSet()}; then try to use id to find configs defined in remote Config Center
* 2. API, directly use id to find configs defined in remote Config Center; if all config instances are defined locally, please use {@link ServiceConfig#setRegistries(List)}
*/
beanDefinition.getPropertyValues().addPropertyValue(beanProperty + "Ids", value);
} else {
Object reference;
if (isPrimitive(type)) {
if ("async".equals(property) && "false".equals(value)
|| "timeout".equals(property) && "0".equals(value)
|| "delay".equals(property) && "0".equals(value)
|| "version".equals(property) && "0.0.0".equals(value)
|| "stat".equals(property) && "-1".equals(value)
|| "reliable".equals(property) && "false".equals(value)) {
// backward compatibility for the default value in old version's xsd
value = null;
}
reference = value;
} else if (ONRETURN.equals(property) || ONTHROW.equals(property) || ONINVOKE.equals(property)) {
int index = value.lastIndexOf(".");
String ref = value.substring(0, index);
String method = value.substring(index + 1);
reference = new RuntimeBeanReference(ref);
beanDefinition.getPropertyValues().addPropertyValue(property + METHOD, method);
} else {
// 设置ref属性值
if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) {
BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
if (!refBean.isSingleton()) {
throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>");
}
}
reference = new RuntimeBeanReference(value);
}
beanDefinition.getPropertyValues().addPropertyValue(beanProperty, reference);
}
}
}
}
}
}
NamedNodeMap attributes = element.getAttributes();
int len = attributes.getLength();
for (int i = 0; i < len; i++) {
Node node = attributes.item(i);
String name = node.getLocalName();
if (!props.contains(name)) {
if (parameters == null) {
parameters = new ManagedMap();
}
String value = node.getNodeValue();
parameters.put(name, new TypedStringValue(value, String.class));
}
}
if (parameters != null) {
beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
}
return beanDefinition;
}
}
参考:https://blog.csdn.net/prestigeding/article/details/80490338

浙公网安备 33010602011771号