您好,登錄后才能下訂單哦!
用途
項目中使用了 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")); } }
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對億速云的支持。如果你想了解更多相關內容請查看下面相關鏈接
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。