作者:畢來生
微信:878799579
前言
個人比較看好Spring Cloud Alibaba家族。此係列以Nacos爲主題,從Spring、Spring boot、Spring Cloud多個方面逐步進行演示,源碼解讀。目前來看官方文檔還有待完善。網絡上除了官網外缺少Nacos系列文章。都是零零散散的知識點。如此係列文章哪裏寫的有不周全,錯誤之處。歡迎大家指正。謝謝。
因公衆號排版問題,可能會有代碼顯示不完整,請使用電腦版微信內置瀏覽器/複製鏈接到瀏覽器中。
1、Nacos是什麼?
來自官網提供Nacos說明
服務(Service)是 Nacos 世界的一等公民。Nacos 支持幾乎所有主流類型的“服務”的發現、配置和管理:
Nacos 的關鍵特性包括一下等等:
服務發現和服務健康監測
動態配置服務
動態 DNS 服務
服務及其元數據管理
Nacos架構圖
2、準備工作
工具:IDEA2018.3 、JDK: 1.8、Maven:3.5(通用配置。後續不在提及此部分。均已此版本演示)
Nacos:0.7.0(寫此文章時最新版本,如後續更新。以最新版本給大家演示)
環境:Windows(演示用,後續更新完成後會有一章在linux下演示。有坑,但原理一樣。不多贅述。)
Nacos穩定版本:https://github.com/alibaba/nacos/releases
Linux下請下載tar後解壓。Windows下請下載zip。
unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz
下載後啓動Nacos。Nacos默認啓動端口爲8848,意爲珠穆朗瑪峯高度。如啓動有端口衝突,請自行調整端口。
3、工程結構
上面說了那麼多,現在先整理來看一下我們的工程結構
附上關鍵部分代碼。
NacosConfiguration
package org.nacos.spring;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import org.springframework.beans.factory.annotation.Configurable;
/**
* @Author: bilaisheng
* @Wechat: 878799579
* @Date: 2019/1/13 19:28
* @Todo: NacosConfiguration,用以註冊以及測試Service Name : nacos-spring
* @Version : JDK1.8 , IDEA2018
*/
@Configurable
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySource(dataId = "nacos-spring", autoRefreshed = true)
public class NacosConfiguration {
}
@EnableNacosConfig
註解啓用 Nacos Spring 的配置管理服務。- @NacosPropertySource
加載了
dataId爲
nacos-spring`的配置源,並開啓自動更新。 - 對 Nacos Spring 的用戶來說,在自身應用中就只是設置 “autoRefreshed” 的一個布爾值。然後在需要修改配置的時候,調用 Nacos 修改配置的接口,或使用 Nacos 的控制檯去修改,配置發生變更後, Nacos 就會把最新的配置推送到該應用的所有機器上。
NacosDiscoveryController
package org.nacos.spring.controller;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* @Author: bilaisheng
* @Wechat: 878799579
* @Date: 2019/1/13 19:29
* @Todo: NacosDisCoveryTest
* @Version : JDK1.8 , IDEA2018
*/
@Controller
@RequestMapping("nacos")
public class NacosDiscoveryController {
@NacosInjected
private NamingService namingService;
@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
private boolean useLocalCache;
@RequestMapping("/{str}")
public String helloNacos(@PathVariable String str){
return new Date() + "Hello Nacos " + str;
}
@RequestMapping("/instance")
@ResponseBody
public List<Instance> getInstance(@PathVariable String serviceName) throws NacosException {
return namingService.getAllInstances(serviceName);
}
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public boolean get() {
return useLocalCache;
}
}
此文件爲普通Spring映射控制器,話說Nacos Spring還是小馬哥@mercyblitz親自操刀。大家可以不用懷疑質量啦。相信很多同學都快被小馬哥逼的要勸退了。
着重說明一下,這個也是Nacos中常用的方法之一。
@RequestMapping("/instance")
@ResponseBody
public List<Instance> getInstance(@PathVariable String serviceName) throws NacosException {
return namingService.getAllInstances(serviceName);
}
獲取全部實例
List<Instance> getAllInstances(String serviceName) throws NacosException;
List<Instance> getAllInstances(String serviceName, List<String> clusters) throws NacosException;
請求參數
名稱 | 類型 | 描述 |
---|---|---|
serviceName | 字符串 | 服務名 |
clusters | List | 集羣列表 |
返回參數
List 實例列表。
獲取配置
描述
用於服務啓動的時候從 Nacos 獲取配置。
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException
請求參數
參數名 | 參數類型 | 描述 |
---|---|---|
dataId | string | 配置 ID,採用類似 package.class(如com.taobao.tc.refund.log.level)的命名規則保證全局唯一性,class 部分建議是配置的業務含義。全部字符小寫。只允許英文字符和 4 種特殊字符("."、":"、"-"、"_"),不超過 256 字節。 |
group | string | 配置分組,建議填寫產品名:模塊名(Nacos:Test)保證唯一性,只允許英文字符和4種特殊字符("."、":"、"-"、"_"),不超過128字節。 |
timeout | long | 讀取配置超時時間,單位 ms,推薦值 3000。 |
返回值
參數類型 | 描述 |
---|---|
string | 配置值 |
請求示例
try {
String serverAddr = "{serverAddr}";
String dataId = "{dataId}";
String group = "{group}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
String content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
} catch (NacosException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
上述兩個文件中關於Nacos使用,請參考官網NacosSDK。裏面詳細標註了每個方法以及對應參數以及測試案例。
父pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.bilaisheng.nacos</groupId>
<artifactId>nacos-spring-examples</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>nacos-spring-discvoery</module>
</modules>
<name>nacos-spring-examples</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.framework.version>5.1.3.RELEASE</spring.framework.version>
<servlet-api.version>4.0.1</servlet-api.version>
<nacos-spring-context.version>0.2.2-RC1</nacos-spring-context.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.nacos/nacos-spring-context -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-spring-context</artifactId>
<version>${nacos-spring-context.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
本工程pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>nacos-spring-examples</artifactId>
<groupId>org.bilaisheng.nacos</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-spring-discvoery</artifactId>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.nacos/nacos-spring-context -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-spring-context</artifactId>
</dependency>
</dependencies>
</project>
頁面請求
頁面請求同普通Spring相同,啓動後根據http://ip:端口/controller/xxx。