用途
項(xiàng)目中使用了 dubbo,注冊(cè)中心使用的 zookeeper,使用 zookeeper 實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的分布式鎖(依賴 curator),因?yàn)榕渲梦募嬖?dubbo.registry 配置,為了直接使用這個(gè)地址來(lái)創(chuàng)建分布式鎖,寫了一個(gè)簡(jiǎn)單的方法來(lái)提取 zookeeper 地址。
效果
dubbo.registry 有多種配置方式,支持所有情況,下面是常見(jiàn)的例子和提取結(jié)果:
1
2
3
4
5
6
7
8
9
|
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 ] |
代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/isea533/article/details/84062301