Nacos提供完整的Java SDK,便於配置管理和服務發現及管理,以 Nacos-0.8.0
版本爲例html
添加Maven依賴:java
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>0.8.0</version>
</dependency>
複製代碼
僅僅引入nacos-client
是不夠的,不然啓動時會出現以下錯誤:git
sun.misc.Launcher$AppClassLoader@18b4aac2 JM.Log:WARN Init JM logger with NopLoggerFactory, pay attention. sun.misc.Launcher$AppClassLoader@18b4aac2
java.lang.ClassNotFoundException: org.apache.logging.log4j.core.Logger
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.alibaba.nacos.client.logger.log4j2.Log4j2LoggerFactory.<init>(Log4j2LoggerFactory.java:33)
at com.alibaba.nacos.client.logger.LoggerFactory.<clinit>(LoggerFactory.java:59)
at com.alibaba.nacos.client.config.utils.LogUtils.<clinit>(LogUtils.java:49)
at com.alibaba.nacos.client.config.NacosConfigService.<clinit>(NacosConfigService.java:55)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.alibaba.nacos.api.config.ConfigFactory.createConfigService(ConfigFactory.java:40)
at com.alibaba.nacos.api.config.ConfigFactory.createConfigService(ConfigFactory.java:59)
at com.alibaba.nacos.api.NacosFactory.createConfigService(NacosFactory.java:52)
at com.learn.nacos.config.NacosConfig.main(NacosConfig.java:12)
複製代碼
根據錯誤提示,應該還須要添加log4j
相關依賴,官網的文檔並無對此說明,我在pom.xml
添加了下面這些依賴纔不報錯github
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
</dependency>
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
複製代碼
建立ConfigService
,能夠經過 NacosFactory.createConfigService()
或 ConfigFactory.createConfigService()
來建立,後者是前者的底層實現方式,這兩種方式都包含以下兩個方法:算法
createConfigService(serverAddr)
createConfigService(properties)
spring
建立示例:apache
// 方式一
String serverAddr = "127.0.0.1:8848";
ConfigService configService = ConfigFactory.createConfigService(serverAddr);
// 方式二
ConfigService configService = ConfigFactory.createConfigService(properties)
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
複製代碼
查看ConfigService
源碼,它提供了以下方法:c#
獲取 Nacos Server 當前狀態:String getServerStatus()
api
底層源碼:緩存
public String getServerStatus() {
if (worker.isHealthServer()) {
return "UP";
} else {
return "DOWN";
}
}
複製代碼
根據源碼註釋,該狀態應該是指 Nacos Server 的狀態,我把 Nacos Server 關閉以後,再次運行示例,獲得的結果仍然是
UP
,不知道這是否是一個BUG。
發佈配置:boolean publishConfig(String dataId, String group, String content) throws NacosException
支持程序自動發佈Nacos配置,建立和修改配置使用同一個方法,配置不存在則建立;配置已存在則更新。
底層源碼:
try {
result = agent.httpPost(url, headers, params, encode, POST_TIMEOUT);
} catch (IOException ioe) {
log.warn("NACOS-0006",
LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0006", "環境問題", "[publish-single] exception"));
log.warn(agent.getName(), "[publish-single] exception, dataId={}, group={}, msg={}", dataId, group,
ioe.toString());
return false;
}
複製代碼
發佈配置後,若是立刻用getConfig()讀取配置,有時候會讀不到,設置了足夠的等待時長後纔可保證每次正常讀取,看了源碼才知道Nacos的配置管理(發佈、讀取、移除)都是經過HTTP接口完成的,但發佈配置的時延是多少,官網彷佛沒有說明?幾秒鐘的時延在一些對實時性要求很高的場景會不會存在影響呢?
讀取配置:String getConfig(String dataId, String group, long timeoutMs) throws NacosException
timeoutMs指讀取配置超時時間,官網推薦設置爲3000
ms
底層源碼:
// 優先使用本地配置
String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant);
if (content != null) {
log.warn(agent.getName(), "[get-config] get failover ok, dataId={}, group={}, tenant={}, config={}", dataId,
group, tenant, ContentUtils.truncateContent(content));
cr.setContent(content);
configFilterChainManager.doFilter(null, cr);
content = cr.getContent();
return content;
}
try {
content = worker.getServerConfig(dataId, group, tenant, timeoutMs);
cr.setContent(content);
configFilterChainManager.doFilter(null, cr);
content = cr.getContent();
return content;
} catch (NacosException ioe) {
if (NacosException.NO_RIGHT == ioe.getErrCode()) {
throw ioe;
}
log.warn("NACOS-0003",
LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0003", "環境問題", "get from server error"));
log.warn(agent.getName(), "[get-config] get from server error, dataId={}, group={}, tenant={}, msg={}",
dataId, group, tenant, ioe.toString());
}
複製代碼
從源碼上看,配置會先從本地緩存文件讀取,若是沒讀取到,纔會去請求Nacos Server的配置,這個緩存文件在哪呢?就在當前用戶的nacos目錄下 生成的緩存文件:nacos/config/fixed-127.0.0.1_8848_nacos/snapshot/DEFAULT_GROUP/nacos-sdk-java-config,配置內容和發佈到Nacos Server的配置內容是一致的。
移除配置:boolean removeConfig(String dataId, String group) throws NacosException
支持程序自動發佈Nacos配置,配置不存在時會直接返回成功,移除配置後,本地的緩存文件也會被刪除
底層源碼:
try {
result = agent.httpDelete(url, null, params, encode, POST_TIMEOUT);
} catch (IOException ioe) {
log.warn("[remove] error, " + dataId + ", " + group + ", " + tenant + ", msg: " + ioe.toString());
return false;
}
複製代碼
移除配置同發佈配置同樣,若是移除後立刻查詢,有可能還能將剛移除的配置查出來,也存在必定的時延,須要設置等待時間讀取。
添加配置監聽:void addListener(String dataId, String group, Listener listener) throws NacosException
支持動態監聽配置的變化,運行示例源碼,在Nacos控制檯把配置內容修改成sdk-java-config:change from nacos console
,此時觀看IDE控制檯,你會看到以下打印信息:
當前線程:com.alibaba.nacos.client.Worker.longPollingfixed-127.0.0.1_8848 ,監聽到配置內容變化:sdk-java-config:change from nacos console
複製代碼
移除配置監聽:void removeListener(String dataId, String group, Listener listener)
移除監聽後,配置的變化不會再監聽
啓動完整示例,運行結果以下,請注意配置監聽線程和配置管理線程不是同一個線程
當前線程:main ,服務狀態:UP
添加監聽
添加監聽成功
發佈配置
發佈配置成功
當前線程:com.alibaba.nacos.client.Worker.longPollingfixed-127.0.0.1_8848 ,監聽到配置內容變化:nacos-sdk-java-config:init
當前線程:main ,發佈配置後獲取配置內容:nacos-sdk-java-config:init
從新發布配置
從新發布配置成功
當前線程:main ,從新發布配置後獲取配置內容:sdk-java-config:update
當前線程:com.alibaba.nacos.client.Worker.longPollingfixed-127.0.0.1_8848 ,監聽到配置內容變化:sdk-java-config:update
當前線程:com.alibaba.nacos.client.Worker.longPollingfixed-127.0.0.1_8848 ,監聽到配置內容變化:sdk-java-config:change from nacos console
移除配置
移除配置成功
當前線程:main ,移除配置後獲取配置內容:null
取消監聽
取消監聽成功
複製代碼
建立NamingService
,能夠經過 NacosFactory.createNamingService()
或 NamingFactory.createNamingService()
來建立,後者是前者的底層實現方式,這兩種方式都包含以下兩個方法:
createNamingService(serverAddr)
createNamingService(properties)
建立示例:
// 方式一
String serverAddr = "127.0.0.1:8848";
NamingService namingService = NamingFactory.createNamingService(serverAddr);
// 方式二
NamingService namingService = NamingFactory.createNamingService(properties)
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
複製代碼
查看NamingService
類源碼,它提供了以下方法:
獲取 Nacos Server 當前狀態:String getServerStatus()
註冊服務實例:void registerInstance(多個參數)
方式一:
String serverIp = "127.0.0.1";
int serverPort = 8848;
String serverAddr = serverIp + ":" + serverPort;
String serviceName = "nacos-sdk-java-discovery";
NamingService namingService = NamingFactory.createNamingService(serverAddr);
namingService.registerInstance(serviceName, serverIp, serverPort);
方式二:
Instance instance = new Instance();
instance.setIp(serverIp);//IP
instance.setPort(serverPort);//端口
instance.setServiceName(serviceName);//服務名
instance.setEnabled(true);//true: 上線 false: 下線
instance.setHealthy(healthy);//健康狀態
instance.setWeight(1.0);//權重
instance.addMetadata("nacos-sdk-java-discovery", "true");//元數據
NamingService namingService = NamingFactory.createNamingService(serverAddr);
namingService.registerInstance(serviceName, instance);
複製代碼
註冊後,本地會生成緩存文件 一、在Nacos安裝目錄data目錄下:data/naming/data/public/com.alibaba.nacos.naming.domains.meta.public##nacos-sdk-java-discovery 二、當前用戶的nacos目錄下:/nacos/naming/public/failover/nacos-sdk-java-discovery 三、當前用戶的nacos目錄下:/nacos/naming/public/nacos-sdk-java-discovery
即便刪除服務實例,上面三個緩存文件也不會被刪除,Nacos控制檯服務列表中該服務也還存在着(但服務實例數會變成0);刪除Nacos控制檯的該服務,安全目錄data目錄下的緩存文件會被刪除,但當前用戶的nacos目錄下的文件不會被刪除,這裏面是什麼機制,我暫時還沒整明白,等後面整明白了再來補充。
刪除服務實例:void deregisterInstance(多個參數)
獲取全部服務實例:List<Instance> getAllInstances(多個參數)
獲取全部健康或不健康的服務實例:List<Instance> selectInstances(多個參數)
隨機獲取一個健康實例(根據負載均衡算法):Instance selectOneHealthyInstance(多個參數)
添加服務實例監聽:void subscribe(多個參數)
添加服務實例監聽:void unsubscribe(多個參數)
分頁獲取全部服務實例:ListView<String> getServicesOfServer(多個參數)
獲取全部監聽的服務實例:List<ServiceInfo> getSubscribeServices()
啓動完整示例,運行結果以下,請注意服務實例監聽線程和服務實例管理線程不是同一個線程
當前線程:main ,服務狀態:UP
註冊實例
註冊實例成功
添加監聽
添加監聽成功
當前線程:main ,註冊實例後獲取全部實例:[{"clusterName":"DEFAULT","enabled":true,"instanceId":"127.0.0.1#8848#DEFAULT#nacos-sdk-java-discovery","ip":"127.0.0.1","metadata":{},"port":8848,"serviceName":"nacos-sdk-java-discovery","valid":true,"weight":1.0}]
當前線程:main ,註冊實例後獲取全部健康實例:[{"clusterName":"DEFAULT","enabled":true,"instanceId":"127.0.0.1#8848#DEFAULT#nacos-sdk-java-discovery","ip":"127.0.0.1","metadata":{},"port":8848,"serviceName":"nacos-sdk-java-discovery","valid":true,"weight":1.0}]
當前線程:com.alibaba.nacos.naming.client.listener ,監聽到實例名稱:nacos-sdk-java-discovery
當前線程:com.alibaba.nacos.naming.client.listener ,監聽到實例內容:[{"clusterName":"DEFAULT","enabled":true,"instanceId":"127.0.0.1#8848#DEFAULT#nacos-sdk-java-discovery","ip":"127.0.0.1","metadata":{},"port":8848,"serviceName":"nacos-sdk-java-discovery","valid":true,"weight":1.0}]
當前線程:main ,註冊實例後獲取一個健康實例:{"clusterName":"DEFAULT","enabled":true,"instanceId":"127.0.0.1#8848#DEFAULT#nacos-sdk-java-discovery","ip":"127.0.0.1","metadata":{},"port":8848,"serviceName":"nacos-sdk-java-discovery","valid":true,"weight":1.0}
當前線程:com.alibaba.nacos.naming.client.listener ,監聽到實例名稱:nacos-sdk-java-discovery
當前線程:com.alibaba.nacos.naming.client.listener ,監聽到實例內容:[{"clusterName":"DEFAULT","enabled":true,"instanceId":"127.0.0.1#8848#DEFAULT#nacos-sdk-java-discovery","ip":"127.0.0.1","metadata":{"change":"true;"},"port":8848,"serviceName":"nacos-sdk-java-discovery","valid":true,"weight":2.0}]
取消監聽
取消監聽成功
刪除實例
刪除實例成功
Exception in thread "main" java.lang.IllegalStateException: no host to srv for serviceInfo: nacos-sdk-java-discovery
at com.alibaba.nacos.client.naming.core.Balancer$RandomByWeight.selectAll(Balancer.java:45)
at com.alibaba.nacos.client.naming.core.Balancer$RandomByWeight.selectHost(Balancer.java:53)
at com.alibaba.nacos.client.naming.NacosNamingService.selectOneHealthyInstance(NacosNamingService.java:270)
at com.alibaba.nacos.client.naming.NacosNamingService.selectOneHealthyInstance(NacosNamingService.java:263)
at com.alibaba.nacos.client.naming.NacosNamingService.selectOneHealthyInstance(NacosNamingService.java:253)
at com.learn.nacos.discovery.NacosDiscovery.main(NacosDiscovery.java:121)
當前線程:main ,刪除實例後獲取全部實例:[]
當前線程:main ,刪除實例後獲取全部健康實例:[]
複製代碼
以上就是 Nacos Java SDK 配置管理和服務管理功能的介紹,請參考示例源碼學習。
項目:learn-nacos-sdk-java
代碼已上傳至碼雲
和Github
上,歡迎下載學習
[Nacos系列:歡迎來到Nacos的世界!][4]
[Nacos系列:基於Nacos的註冊中心][5]
[Nacos系列:基於Nacos的配置中心][6]