从dubbo zookeeper注册地址提取出zookeeper地址的方法

时间:2021-05-19

用途

项目中使用了 dubbo,注册中心使用的 zookeeper,使用 zookeeper 实现了一个简单的分布式锁(依赖 curator),因为配置文件存在 dubbo.registry 配置,为了直接使用这个地址来创建分布式锁,写了一个简单的方法来提取 zookeeper 地址。

效果

dubbo.registry 有多种配置方式,支持所有情况,下面是常见的例子和提取结果:

zookeeper://localhost:2181zookeeper://localhost:2181?client=zkclientzookeeper://localhost:2181?backup=localhost:2182,localhost:2183zookeeper://localhost:2181?client=zkclient&backup=localhost:2182,localhost:2183------------结果------------Optional[localhost:2181]Optional[localhost:2181]Optional[localhost:2181,localhost:2182,localhost:2182]Optional[localhost:2181,localhost:2183,localhost:2183]

代码

import java.util.Optional;public class ZookeeperURL { public static final String PREFIX = "zookeeper://"; public static final String BACKUP = "backup="; public static Optional<String> convertDubboRegistryToZookeeperURL(String dubboRegistry){ StringBuilder zookeeperURL = new StringBuilder(); if(dubboRegistry != null && dubboRegistry.startsWith(PREFIX)){ dubboRegistry = dubboRegistry.substring(PREFIX.length()); int index = dubboRegistry.indexOf("?"); if(index > 0){ zookeeperURL.append(dubboRegistry.substring(0, index)); dubboRegistry = dubboRegistry.substring(index + 1); String[] dubboRegistries = dubboRegistry.split("&"); for (int i = 0; i < dubboRegistries.length; i++) { if(dubboRegistries[i].startsWith(BACKUP)){ String[] backups = dubboRegistries[i].substring(BACKUP.length()).split(","); for (int j = 0; j < backups.length; j++) { zookeeperURL.append(",").append(backups[i]); } } } } else { zookeeperURL.append(dubboRegistry); } return Optional.of(zookeeperURL.toString()); } return Optional.empty(); } public static void main(String[] args) { System.out.println(convertDubboRegistryToZookeeperURL("zookeeper://localhost:2181")); System.out.println(convertDubboRegistryToZookeeperURL("zookeeper://localhost:2181?client=zkclient")); System.out.println(convertDubboRegistryToZookeeperURL("zookeeper://localhost:2181?backup=localhost:2182,localhost:2183")); System.out.println(convertDubboRegistryToZookeeperURL("zookeeper://localhost:2181?client=zkclient&backup=localhost:2182,localhost:2183")); }}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章