Spring Cloud Alibaba基礎教程第一篇:使用Nacos實現服務註冊與發現

一. 什麼是Nacos

Nacos(官方網站:http://nacos.io)是一個易於使用的平臺,專爲動態服務發現,配置和服務管理而設計。它能夠幫助您輕鬆構建雲本機應用程序和微服務平臺。java

安裝並啓動Nacos

下載地址:github.com/alibaba/nac… 本文版本:1.0.1git

下載完成以後,解壓。github

cd 到nacos/bin目錄下web

根據不一樣平臺,執行不一樣命令,啓動Nacos服務:spring

啓動命令(standalone表明着單機模式運行,非集羣模式):apache

  • Linux/Unix/Mac:sh startup.sh -m standalone
  • Windows:cmd startup.cmd -m standalone或者雙擊startup.cmd運行文件。

不出意外 你會啓動成功 啓動完成以後,訪問:http://localhost:8848/nacos/,能夠進入Nacos的服務管理頁面,具體以下:瀏覽器

默認用戶名/密碼: nacos/nacos 登陸便可 目前Nacos註冊中心搭建完畢bash

建立服務模擬微服務

項目結構圖:app

  • Spring Boot: 2.1.6.RELEASE負載均衡

  • Spring Cloud: Greenwich.SR1

  • Spring Cloud Alibaba: 0.2.2.RELEASE

教程採用多模塊化,先建立maven項目做爲父項目,引入公共依賴

完整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>com.xd</groupId>
    <artifactId>SpringCloudAlibabaLearn</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/>
    </parent>

    <modules>
        <module>alibaba-nacos-provider-server</module>
        <module>alibaba-nacos-consumer-server</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>0.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
複製代碼

上述內容主要三部分:

  • parent:定義spring boot的版本
  • dependencyManagement:spring cloud的版本以及spring cloud alibaba的版本,因爲spring cloud alibaba還未歸入spring cloud的主版本管理中,因此須要本身加入
  • dependencies:當前應用要使用的依賴內容。這裏主要新加入了Nacos的服務註冊與發現模塊:

spring-cloud-starter-alibaba-nacos-discovery。因爲在dependencyManagement中已經引入了版本,因此這裏就不用指定具體版本了。還有就是spring-boot的起步依賴

下面在父模塊上建立兩個應用(服務提供者與服務消費者)來驗證服務的註冊與發現

建立服務提供者

1. 建立SpringBoot項目

而後命項目名,組織名等便可

2.編輯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>
   <parent>
      <groupId>com.xd</groupId>
      <artifactId>SpringCloudAlibabaLearn</artifactId>
      <version>1.0-SNAPSHOT</version>
      <relativePath>../</relativePath>
   </parent>
   <artifactId>alibaba-nacos-provider-server</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>alibaba-nacos-provider-server</name>
   <description>服務提供者</description>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
複製代碼
3.application.properties

配置服務名稱和nacos註冊地址

# 自定義端口號
server.port=8080
# 服務提供者
spring.application.name=provider-service
# 註冊到nacos註冊中心
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
複製代碼
4.建立請求類,並實現一個接口
package com.xd.alibabanacosproviderserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @RestController 表示控制層
 * @EnableDiscoveryClient 開啓服務註冊發現功能
 */
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class AlibabaNacosProviderServerApplication {

   public static void main(String[] args) {
      SpringApplication.run(AlibabaNacosProviderServerApplication.class, args);
   }

   @GetMapping("/echo/{name}")
   public String echo(@PathVariable String name) {
      return "hello " + name;
   }
}
複製代碼

主要表示:

@SpringBootApplication定義是個Spring Boot應用;

@EnableDiscoveryClient開啓Spring Cloud的服務註冊與發現,因爲這裏引入了spring-cloud-starter-alibaba-nacos-discovery模塊,因此Spring Cloud Common中定義的那些與服務治理相關的接口將使用Nacos的實現

5.啓動程序

啓動程序完成後你會發現控制檯打印的 說明已經向nacos完成註冊

6.查看nacos註冊中心查詢是否註冊

切換到服務列表: 這裏會顯示當前註冊的全部服務,以及每一個服務的集羣數目、實例數、健康實例數。

點擊詳情,咱們還能看到每一個服務具體的實例信息,以下圖所示:

目前爲止服務提供者建立完畢

建立服務消費者

1.建立Spring Boot項目

步驟同上,這裏不作多解釋

2.編輯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>
   <parent>
      <groupId>com.xd</groupId>
      <artifactId>SpringCloudAlibabaLearn</artifactId>
      <version>1.0-SNAPSHOT</version>
      <relativePath>../</relativePath>
   </parent>
   <artifactId>alibaba-nacos-provider-server</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>alibaba-nacos-provider-server</name>
   <description>服務消費者</description>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
複製代碼
3.application.properties

配置服務名稱和nacos註冊地址

server.port=8081
#服務消費者
spring.application.name=consumer-service
#註冊服務到nacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
複製代碼
4.建立應用主類,並實現一個接口,在該接口中調用服務提供方的接口。
package com.xd.alibabanacosconsumerserver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @RestController 表示控制層
 * @EnableDiscoveryClient 開啓服務註冊發現功能
 */
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class AlibabaNacosConsumerServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(AlibabaNacosConsumerServerApplication.class, args);
    }


    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("/echo/{name}")
    public String test(@PathVariable("name") String name) {
        // 經過spring cloud common中的負載均衡接口選取服務提供節點實現接口調用
        // serviceId爲spring.application.name
        ServiceInstance serviceInstance = loadBalancerClient.choose("provider-service");
        String url = serviceInstance.getUri() + "/echo/" + name;
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        return "from: " + url + ",return: " + result;
    }
}
複製代碼

這裏使用了Spring Cloud Common中的LoadBalancerClient接口來挑選服務實例信息。而後從挑選出的實例信息中獲取可訪問的URI,拼接上服務提供方的接口規則來發起調用。

5.啓動服務消費者程序

一樣的打開nacos註冊中心有沒有註冊成功

看來都已經註冊成功,而後打開瀏覽器訪問: http://localhost:8081/echo/lhd

能夠看到,發送請求時,已經成功調用並返回信息 本文模擬在微服務中服務與服務之間相互調用的過程,可是很明顯,這樣的實現仍是比較繁瑣,後面講解服務消費的幾種方式

四. 參考資料:

五. 代碼示例

若是您對這些感興趣,歡迎star、follow、收藏、轉發給予支持!

相關文章
相關標籤/搜索