從dubbo zookeeper注冊地址提取出zookeeper地址的方法
用途
項目中使用了 dubbo,注冊中心使用的 zookeeper,使用 zookeeper 實現(xiàn)了一個簡單的分布式鎖(依賴 curator),因為配置文件存在 dubbo.registry 配置,為了直接使用這個地址來創(chuàng)建分布式鎖,寫了一個簡單的方法來提取 zookeeper 地址。
效果
dubbo.registry 有多種配置方式,支持所有情況,下面是常見的例子和提取結(jié)果:
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 ------------結(jié)果------------ 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")); } }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
如何使用BigDecimal實現(xiàn)Java開發(fā)商業(yè)計算
這篇文章主要介紹了如何使用BigDecimal實現(xiàn)Java開發(fā)商業(yè)計算,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09SpringBoot整合mybatis常見問題(小結(jié))
這篇文章主要介紹了SpringBoot整合mybatis常見問題(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12Spring Boot 各種回滾操作實戰(zhàn)教程(自動回滾、手動回滾、部分回滾)
這篇文章主要介紹了Spring Boot 各種回滾操作實戰(zhàn)教程(自動回滾、手動回滾、部分回滾),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07