从 dubbo zookeeper 注册地址提取 zookeeper 地址

本文仅为个人记录,方便以后查阅。

用途

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

效果

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

zookeeper://localhost:2181
zookeeper://localhost:2181?client=zkclient
zookeeper://localhost:2181?backup=localhost:2182,localhost:2183
zookeeper://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"));
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

isea533

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值