Springcloud基础知识(11)- Spring Cloud Alibaba Nacos (一) | Nacos 简介、服务注册中心


Spring Cloud 本身并不是一个拿来即可用的框架,它是一套微服务规范,这套规范共有两代实现。

第一代实现: Spring Cloud Netflix,
第二代实现: Spring Cloud Alibaba。

2018 年 12 月12 日,Netflix 公司宣布 Spring Cloud Netflix 系列大部分组件都进入维护模式,不再添加新特性。这严重地限制了 Spring Cloud 的高速发展,于是各大互联网公司和组织开始把目光转向 Spring Cloud 的第二代实现:Spring Cloud Alibaba。

Spring Cloud Alibaba:

    Spring Cloud Alibaba 是阿里巴巴结合自身丰富的微服务实践而推出的微服务开发的一站式解决方案,是 Spring Cloud 第二代实现的主要组成部分。

    Spring Cloud Alibaba 吸收了 Spring Cloud Netflix 的核心架构思想,并进行了高性能改进。自 Spring Cloud Netflix 进入停更维护后,Spring Cloud Alibaba 逐渐代替它成为主流的微服务框架。

    Spring Cloud Alibaba 是国内首个进入 Spring 社区的开源项目。2018 年 7 月,Spring Cloud Alibaba 正式开源,并进入 Spring Cloud 孵化器中孵化;2019 年 7 月,Spring Cloud 官方宣布 Spring Cloud Alibaba 毕业,并将仓库迁移到 Alibaba Github OSS 下。

    虽然 Spring Cloud Alibaba 诞生时间不久,但俗话说的好“大树底下好乘凉”,依赖于阿里巴巴强大的技术影响力,Spring Cloud Alibaba 在业界得到了广泛的使用,成功案例也越来越多。

Spring Cloud Alibaba 包含了多种开发分布式微服务系统的必需组件:

    (1) Nacos:阿里巴巴开源产品,一个更易于构建云原生应用的动态服务发现,配置管理和服务管理平台。
    (2) Sentinel:阿里巴巴开源产品,把流量作为切入点,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。
    (3) RocketMQ:Apache RocketMQ 是一款基于 Java 的高性能、高吞吐量的分布式消息和流计算平台。
    (4) Dubbo:Apache Dubbo 是一款高性能的 Java RPC 框架。
    (5) Seata:阿里巴巴开源产品,一个易于使用的高性能微服务分布式事务解决方案。
    (6) Alibaba Cloud OSS:阿里云对象存储服务器(Object Storage Service,简称OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。
    (7) Alibaba Cloud Schedulerx:阿里中间件团队开发的一款分布式调度产品,支持周期性的任务与固定时间点触发任务。

    通过 Spring Cloud Alibaba 的这些组件,我们只需要添加一些注解和少量配置,就可以将 Spring Cloud 应用接入阿里微服务解决方案,通过阿里中间件来迅速搭建分布式应用系统。

Spring Cloud Alibaba 的应用场景如下:

    (1) 大型复杂的系统,例如大型电商系统。
    (2) 高并发系统,例如大型门户网站、商品秒杀系统。
    (3) 需求不明确,且变更很快的系统,例如创业公司业务系统。

Spring Cloud 两代实现组件对比:

Spring Cloud Netflix 状态 Spring Cloud Alibaba 状态
Ereka 2.0 孵化失败 Nacos Discovery 性能更好,感知力更强
Ribbon 停更进维 Spring Cloud Loadbalancer Spring Cloud 原生组件,用于代替 Ribbon
Hystrix 停更进维 Sentinel 可视化配置,上手简单
Zuul 停更进维 Spring Cloud Gateway 性能为 Zuul 的 1.6 倍
Spring Cloud Config 搭建复杂,无可视化界面,不容易上手 Nacos Config 搭建简单,有可视化界面,配置管理更简单,容易上手


Spring Cloud、Spring Cloud Alibaba 以及 Spring Boot 之间版本依赖关系如下。

Spring Cloud 版本 Spring Cloud Alibaba 版本 Spring Boot 版本
Spring Cloud 2020.0.1 2021.1 2.4.2
Spring Cloud Hoxton.SR12 2.2.7.RELEASE 2.3.12.RELEASE
Spring Cloud Hoxton.SR9 2.2.6.RELEASE 2.3.2.RELEASE
Spring Cloud Hoxton.SR3 2.2.1.RELEASE 2.2.5.RELEASE
Spring Cloud Hoxton.RELEASE 2.2.0.RELEASE 2.2.X.RELEASE
Spring Cloud Greenwich.SR6 2.1.4.RELEASE 2.1.13.RELEASE
Spring Cloud Greenwich 2.1.2.RELEASE 2.1.X.RELEASE
Spring Cloud Finchley 2.0.4.RELEASE(停止维护,建议升级) 2.0.X.RELEASE
Spring Cloud Edgware 1.5.1.RELEASE(停止维护,建议升级) 1.5.X.RELEASE


Spring Cloud Alibaba 下各组件版本关系如下表。

Spring Cloud Alibaba 版本 Sentinel 版本 Nacos 版本 RocketMQ 版本 Dubbo 版本 Seata 版本
2.2.7.RELEASE 1.8.1 2.0.3 4.6.1 2.7.13 1.3.0
2.2.6.RELEASE  1.8.1 1.4.2 4.4.0 2.7.8 1.3.0

2021.1

2.2.5.RELEASE

2.1.4.RELEASE

2.0.4.RELEASE

1.8.0 1.4.1 4.4.0 2.7.8 1.3.0

2.2.3.RELEASE

2.1.3.RELEASE

2.0.3.RELEASE

1.8.0 1.3.3 4.4.0 2.7.8 1.3.0

2.2.1.RELEASE 

2.1.2.RELEASE

2.0.2.RELEASE

1.7.1 1.2.1 4.4.0 2.7.6 1.2.0

2.2.0.RELEASE

1.7.1 1.1.4 4.4.0 2.7.4 1.0.0

2.1.1.RELEASE

2.0.1.RELEASE

1.5.1.RELEASE

1.7.0 1.1.4 4.4.0 2.7.3 0.9.0

2.1.0.RELEASE

2.0.0.RELEASE

1.5.0.RELEASE

1.6.3 1.1.1 4.4.0 2.7.3 0.7.1

 

1. Nacos 简介

    Nacos 英文全称为 Dynamic Naming and Configuration Service,是一个由阿里巴巴团队使用 Java 语言开发的开源项目。

    Nacos 是一个更易于帮助构建云原生应用的动态服务发现、配置和服务管理平台(参考自 Nacos 官网)。

    Nacos 的命名是由 3 部分组成:

组成部分 全称 描述
Na naming/nameServer 即服务注册中心,与 Spring Cloud Eureka 的功能类似。
co configuration 即配置中心,与 Spring Cloud Config+Spring Cloud Bus 的功能类似。
s service 即服务,表示 Nacos 实现的服务注册中心和配置中心都是以服务为核心的。


    可以将 Nacos 理解成服务注册中心和配置中心的组合体,它可以替换 Eureka 作为服务注册中心,实现服务的注册与发现;还可以替换 Spring Cloud Config 作为配置中心,实现配置的动态刷新。

    Nacos 作为服务注册中心经历了十年“双十一”的洪峰考验,具有简单易用、稳定可靠、性能卓越等优点,可以帮助用户更敏捷、容易地构建和管理微服务应用。

    Nacos 支持几乎所有主流类型“服务”的发现、配置和管理:

        Kubernetes Service
        gRPC & Dubbo RPC Service
        Spring Cloud RESTful Service

    Nacos 提供了一系列简单易用的特性,能够帮助我们快速地实现动态服务发现、服务配置等功能。

        (1) 服务发现:Nacos 支持基于 DNS 和 RPC 的服务发现。当服务提供者使用原生 SDK、OpenAPI 或一个独立的 Agent TODO 向 Nacos 注册服务后,服务消费者可以在 Nacos 上通过 DNS TODO 或 HTTP&API 查找、发现服务。

        (2) 服务健康监测:Nacos 提供对服务的实时健康检查,能够阻止请求发送到不健康主机或服务实例上。Nacos 还提供了一个健康检查仪表盘,能够帮助我们根据健康状态管理服务的可用性及流量。

        (3) 动态配置服务: 动态配置服务可以让我们以中心化、外部化和动态化的方式,管理所有环境的应用配置和服务配置。

            动态配置消除了配置变更时重新部署应用和服务的需要,让配置管理变得更加高效、敏捷。

            配置中心化管理让实现无状态服务变得更简单,让服务按需弹性扩展变得更容易。

            Nacos 提供了一个简洁易用的 UI 帮助我们管理所有服务和应用的配置。Nacos 还提供包括配置版本跟踪、金丝雀发布、一键回滚配置以及客户端配置更新状态跟踪在内的一系列开箱即用的配置管理特性,帮助我们更安全地在生产环境中管理配置变更和降低配置变更带来的风险。

        (4) 动态 DNS 服务:Nacos 提供了动态 DNS 服务,能够让我们更容易地实现负载均衡、流量控制以及数据中心内网的简单 DNS 解析服务。Nacos 提供了一些简单的 DNS APIs TODO,可以帮助我们管理服务的关联域名和可用的 IP:PORT 列表。

        (5) 服务及其元数据管理:Nacos 能让我们从微服务平台建设的视角管理数据中心的所有服务及元数据,包括管理服务的描述、生命周期、服务的静态依赖分析、服务的健康状态、服务的流量管理、路由及安全策略、服务的 SLA 以及 metrics 统计数据。


    Nacos 也采用 CS(Client/Server,客户端/服务器)架构,它包含两大组件,如下表。

        (1) Nacos 服务端 (Nacos Server): 与 Eureka Server 不同,Nacos Server 由阿里巴巴团队使用 Java 语言编写并将 Nacos Server 的下载地址给用户,用户只需要直接下载并运行即可。    Nacos Server 可以作为服务注册中心,帮助 Nacos Client 实现服务的注册与发现。 Nacos Server 可以作为配置中心,帮助 Nacos Client 在不重启的情况下,实现配置的动态刷新。

        (2) Nacos 客户端 (Nacos Client): 通常指的是微服务架构中的各个服务,由用户自己搭建,可以使用多种语言编写。    Nacos Client 通过添加依赖 spring-cloud-starter-alibaba-nacos-discovery,在服务注册中心(Nacos Server)中实现服务的注册与发现。Nacos Client 通过添加依赖 spring-cloud-starter-alibaba-nacos-config,在配置中心(Nacos Server)中实现配置的动态刷新。

    Nacos: https://nacos.io/
    Nacos GitHub: https://github.com/alibaba/Nacos


2. Nacos 服务注册中心

    Nacos 作为服务注册中心可以实现服务的注册与发现,涉及到以下 3 个角色:

        (1) 服务注册中心(Register Service):它是一个 Nacos Server,可以为服务提供者和服务消费者提供服务注册和发现功能。
        (2) 服务提供者(Provider Service):它是一个 Nacos Client,用于对外服务。它将自己提供的服务注册到服务注册中心,以供服务消费者发现和调用。
        (3) 服务消费者(Consumer Service):它是一个 Nacos Client,用于消费服务。它可以从服务注册中心获取服务列表,调用所需的服务。

    Nacos 实现服务注册与发现的流程如下:

        (1) 从 Nacos 官方提供的下载页面中,下载 Nacos Server 并运行;
        (2) 服务提供者 Nacos Client 启动时,会把服务以服务名(spring.application.name)的方式注册到服务注册中心(Nacos Server);
        (3) 服务消费者 Nacos Client 启动时,也会将自己的服务注册到服务注册中心;
        (4) 服务消费者在注册服务的同时,它还会从服务注册中心获取一份服务注册列表信息,该列表中包含了所有注册到服务注册中心上的服务的信息(包括服务提供者和自身的信息);
        (5) 在获取了服务提供者的信息后,服务消费者通过 HTTP 或消息中间件远程调用服务提供者提供的服务。


    本文以 Nacos 2.1.0 为例,演示 Windows 下安装和运行 Nacos Server,步骤如下。

 

    1) 下载

 
        浏览器访问 Nacos Server 下载页面(https://github.com/alibaba/nacos/releases/tag/2.1.0),并在页面最下方点击链接 nacos-server-2.1.0.zip。
        
        下载完成后,解压 nacos-server-2.1.0.zip,目录结构如下:

            nacos
                |- bin
                |- conf
                |- target

            各目录说明如下:

                bin:用于存放 Nacos 的可执行命令。
                conf:用于存放 Nacos 配置文件。
                target:用于存放 Nacos 应用的 jar 包。

    2) 单机模式启动
    
        打开命令行窗口,跳转到 Nacos Server 安装目录的 bin 下,执行以下命令,以单机模式启动 Nacos Server。

            > startup -m standalone

 1             "nacos is starting with standalone"
 2 
 3                     ,--.
 4                 ,--.'|
 5             ,--,:  : |                                                Nacos 2.1.0
 6             ,`--.'`|  ' :                       ,---.                 Running in stand alone mode, All function modules
 7             |   :  :  | |                      '   ,'\   .--.--.      Port: 8848
 8             :   |   \ | :  ,--.--.     ,---.  /   /   | /  /    '     Pid: 9992
 9             |   : '  '; | /       \   /     \.   ; ,. :|  :  /`./     Console: http://192.168.0.2:8848/nacos/index.html
10             '   ' ;.    ;.--.  .-. | /    / ''   | |: :|  :  ;_
11             |   | | \   | \__\/: . ..    ' / '   | .; : \  \    `.    https://nacos.io
12             '   : |  ; .' ," .--.; |'   ; :__|   :    |  `----.   \
13             |   | '`--'  /  /  ,.  |'   | '.'|\   \  /  /  /`--'  /
14             '   : |     ;  :   .'   \   :    : `----'  '--'.     /
15             ;   |.'     |  ,     .-./\   \  /            `--'---'
16             '---'        `--`---'     `----'
17 
18             2022-07-12 11:05:13,315 INFO Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@525d79f0' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
19 
20             2022-07-12 11:05:13,324 INFO Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
21 
22             2022-07-12 11:05:13,798 INFO Tomcat initialized with port(s): 8848 (http)
23 
24             2022-07-12 11:05:15,190 INFO Root WebApplicationContext: initialization completed in 5633 ms
25 
26             ...


            注:192.168.0.2 是 Windows 主机的内网 IP,使用本机浏览器测试,可以访问 http://localhost:8848/nacos。

    3) 访问控制台页面

        浏览器访问 “http://localhost:8848/nacos”,跳转到登陆页面,输入登录名和密码(默认 nacos/nacos),点击提交按钮,跳转到 Nacos Server 控制台页面。

        注:在 CentOS 上运行时,需要让防火墙放行 8848,可以运行如下命令:

            $ sudo firewall-cmd --zone=public --add-port=8848/tcp --permanent
            $ sudo firewall-cmd --reload

        取消端口放行,用如下命令:

            $ sudo firewall-cmd --zone=public --remove-port=8848/tcp --permanent
            $ sudo firewall-cmd --reload


3. 服务提供者

    本文参考 “ Springcould基础知识(1)- 微服务、Spring Cloud 简介、IDEA 创建多模块项目 ” ,创建 nacos 服务提供者项目

    1) 创建 Maven 主项目

        运行 IDEA,点击菜单 New 创建 Project:
        
            New Project -> Project Type: Maven -> Project SDK: 1.8 -> Uncheck "Create from archtype" -> Next

                Name: SpringcloudDemo04
                GroupId: com.example
                ArtifactId: SpringcloudDemo04

            -> Finish

        修改 pom.xml 内容如下:

 1             <?xml version="1.0" encoding="UTF-8"?>
 2             <project xmlns="http://maven.apache.org/POM/4.0.0"
 3                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 5                                         http://maven.apache.org/xsd/maven-4.0.0.xsd">
 6                 <parent>
 7                     <groupId>org.springframework.boot</groupId>
 8                     <artifactId>spring-boot-starter-parent</artifactId>
 9                     <version>2.4.2</version>
10                     <relativePath/> <!-- lookup parent from repository -->
11                 </parent>
12 
13                 <modelVersion>4.0.0</modelVersion>
14                 <packaging>pom</packaging>
15 
16                 <groupId>com.example</groupId>
17                 <artifactId>SpringcloudDemo04</artifactId>
18                 <version>1.0-SNAPSHOT</version>
19 
20                 <properties>
21                     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
22                     <maven.compiler.source>1.8</maven.compiler.source>
23                     <maven.compiler.target>1.8</maven.compiler.target>
24                     <junit.version>4.12</junit.version>
25                     <log4j.version>1.2.17</log4j.version>
26                     <lombok.version>1.16.18</lombok.version>
27                     <spring-cloud.version>2020.0.4</spring-cloud.version>
28                     <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
29                 </properties>
30 
31                 <dependencyManagement>
32                     <dependencies>
33                         <!-- Spring Cloud Alibaba 的版本信息 -->
34                         <dependency>
35                             <groupId>com.alibaba.cloud</groupId>
36                             <artifactId>spring-cloud-alibaba-dependencies</artifactId>
37                             <version>${spring-cloud-alibaba.version}</version>
38                             <type>pom</type>
39                             <scope>import</scope>
40                         </dependency>
41                         <!-- Spring Cloud 的版本信息 -->
42                         <dependency>
43                             <groupId>org.springframework.cloud</groupId>
44                             <artifactId>spring-cloud-dependencies</artifactId>
45                             <version>${spring-cloud.version}</version>
46                             <type>pom</type>
47                             <scope>import</scope>
48                         </dependency>
49                     </dependencies>
50                 </dependencyManagement>
51                 
52             </project>


        通过 dependencyManagement 对 Spring Cloud Alibaba 的版本信息进行管理,各子模块在引入 Spring Cloud Alibaba 的组件时不用指定版本号。


    2) 创建 ServiceProvider 子模块

        (1) 创建 Maven 模块

            选择左上的项目列表中的 SpringcloudDemo04,点击鼠标右键,选择 New -> Module 进入 New Module 页面:

                Maven -> Project SDK: 1.8 -> Check "Create from archtype" -> select "org.apache.maven.archtypes:maven-archtype-quickstart" -> Next

                    Name: ServiceProvider
                    GroupId: com.example
                    ArtifactId: ServiceProvider

                -> Finish

        (2) 修改 pom.xml,内容如下。

 1             <?xml version="1.0" encoding="UTF-8"?>
 2             <project xmlns="http://maven.apache.org/POM/4.0.0"
 3                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 5                                         http://maven.apache.org/xsd/maven-4.0.0.xsd">
 6                 <parent>
 7                     <artifactId>SpringcloudDemo04</artifactId>
 8                     <groupId>com.example</groupId>
 9                     <version>1.0-SNAPSHOT</version>
10                 </parent>
11                 <modelVersion>4.0.0</modelVersion>
12 
13                 <artifactId>ServiceProvider</artifactId>
14 
15                 <name>ServiceProvider</name>
16                 <!-- FIXME change it to the project's website -->
17                 <url>http://www.example.com</url>
18 
19                 <properties>
20                     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21                     <maven.compiler.source>1.8</maven.compiler.source>
22                     <maven.compiler.target>1.8</maven.compiler.target>
23                     <maven.install.skip>true</maven.install.skip>
24                 </properties>
25 
26                 <dependencies>
27                     <dependency>
28                         <groupId>junit</groupId>
29                         <artifactId>junit</artifactId>
30                         <scope>test</scope>
31                     </dependency>
32                     <dependency>
33                         <groupId>org.springframework.boot</groupId>
34                         <artifactId>spring-boot-starter-web</artifactId>
35                     </dependency>        
36                     <dependency>
37                         <groupId>org.springframework.boot</groupId>
38                         <artifactId>spring-boot-starter-test</artifactId>
39                         <scope>test</scope>
40                     </dependency>
41                     <!--Spring Cloud Alibaba Nacos discovery -->
42                     <dependency>
43                         <groupId>com.alibaba.cloud</groupId>
44                         <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
45                     </dependency>        
46                 </dependencies>
47 
48                 <build>
49                     <plugins>
50                         <plugin>
51                             <groupId>org.springframework.boot</groupId>
52                             <artifactId>spring-boot-maven-plugin</artifactId>
53                             <configuration>
54                                 <mainClass>com.example.App</mainClass>
55                                 <layout>JAR</layout>
56                             </configuration>
57                             <executions>
58                                 <execution>
59                                     <goals>
60                                         <goal>repackage</goal>
61                                     </goals>
62                                 </execution>
63                             </executions>
64                         </plugin>
65                     </plugins>
66                 </build>
67 
68             </project>


        (3) 创建 src/main/resources/application.yml 文件

1             server:
2                 port: 8001  # 端口号
3             spring:
4                 application:
5                     name: alibaba-service-provider   # 服务名
6                 cloud:
7                     nacos:
8                         discovery:
9                             server-addr: 127.0.0.1:8848  # Nacos server 的地址

        (4) 创建 src/main/java/com/example/controller/IndexController.java 文件

 1             package com.example.controller;
 2 
 3             import org.springframework.beans.factory.annotation.Value;
 4             import org.springframework.web.bind.annotation.GetMapping;
 5             import org.springframework.web.bind.annotation.PathVariable;
 6             import org.springframework.web.bind.annotation.RestController;
 7 
 8             @RestController
 9             public class IndexController {
10                 @Value("${server.port}")
11                 private String serverPort;
12                 @Value("${spring.application.name}")
13                 private String appName;
14 
15                 @GetMapping(value = "/service/{id}")
16                 public String getService(@PathVariable("id") Integer id) {
17 
18                     String str = "<h2>Nacos - Service Provider</h2>";
19                     str += "<p>Service Name: " + appName + "<br>";
20                     str += "Port: " + serverPort + "<br>";
21                     str += "Id: " + id + "</p>";
22 
23                     return str;
24                 }
25             }


        (5) 修改 src/main/java/com/example/App.java 文件

 1             package com.example;
 2 
 3             import org.springframework.boot.SpringApplication;
 4             import org.springframework.boot.autoconfigure.SpringBootApplication;
 5             import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 6 
 7             @SpringBootApplication
 8             @EnableDiscoveryClient  // 开启服务发现功能
 9             public class App {
10                 public static void main(String[] args) {
11                     SpringApplication.run(App.class, args);
12                 }
13             }


        (6) 打包运行

            菜单 Run -> Edit Configurations (或工具条上选择) —> 进入 Run/Debug Configurations 页面 -> Click "+" add new configuration -> Select "Maven":

                Working directory: ServiceProvider 所在路径
                Command line: clean package

            -> Apply / OK

            Click Run "ServiceProvider [clean, package]" ,jar 包生成在目录 target/ 里

                ServiceProvider-1.0-SNAPSHOT.jar
                ServiceProvider-1.0-SNAPSHOT.jar.original  

            打开 cmd 命令行窗口,进入 ServiceProvider 模块目录,运行以下命令:

                java -jar target\ServiceProvider-1.0-SNAPSHOT.jar

            浏览器访问 “http://localhost:8001/service/1”,结果如下。

                Nacos - Service Provider
                Service Name: alibaba-service-provider
                Port: 8001
                Id: 1

            访问 “http://localhost:8848/nacos”,查看 “服务管理” 下的 “服务列表”,结果如下。

                服务名                       分组名称        集群数目 实例数  健康实例数 触发保护阈值
            alibaba-service-provider  DEFAULT_GROUP    1        1         1          false


4. 服务消费者

    在主项目 SpringcloudDemo04 下创建 Consumer 子模块。

    1) 创建 Maven 模块

        选择左上的项目列表中的 SpringcloudDemo04,点击鼠标右键,选择 New -> Module 进入 New Module 页面:

            Maven -> Project SDK: 1.8 -> Check "Create from archtype" -> select "org.apache.maven.archtypes:maven-archtype-quickstart" -> Next

                Name: Consumer
                GroupId: com.example
                ArtifactId: Consumer

            -> Finish

    2) 修改 pom.xml,内容如下。

 1         <?xml version="1.0" encoding="UTF-8"?>
 2         <project xmlns="http://maven.apache.org/POM/4.0.0"
 3                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 5                                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
 6             <parent>
 7                 <artifactId>SpringcloudDemo04</artifactId>
 8                 <groupId>com.example</groupId>
 9                 <version>1.0-SNAPSHOT</version>
10             </parent>
11             <modelVersion>4.0.0</modelVersion>
12 
13             <artifactId>Consumer</artifactId>
14 
15             <name>Consumer</name>
16             <!-- FIXME change it to the project's website -->
17             <url>http://www.example.com</url>
18 
19             <properties>
20                 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21                 <maven.compiler.source>1.8</maven.compiler.source>
22                 <maven.compiler.target>1.8</maven.compiler.target>
23             </properties>
24 
25             <dependencies>
26                 <dependency>
27                     <groupId>junit</groupId>
28                     <artifactId>junit</artifactId>
29                     <scope>test</scope>
30                 </dependency>
31                 <!-- SpringCloud ailibaba nacos discovery -->
32                 <dependency>
33                     <groupId>com.alibaba.cloud</groupId>
34                     <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
35                 </dependency>
36                 <!-- 由于 Netflix Ribbon 进入停更维护阶段,因此新版本的 Nacos discovery 都已经移除了 Ribbon ,此时我们需要引入 loadbalancer 代替 -->
37                 <dependency>
38                     <groupId>org.springframework.cloud</groupId>
39                     <artifactId>spring-cloud-loadbalancer</artifactId>
40                 </dependency>
41                 <dependency>
42                     <groupId>org.springframework.boot</groupId>
43                     <artifactId>spring-boot-starter-web</artifactId>
44                 </dependency>
45                 <dependency>
46                     <groupId>org.springframework.boot</groupId>
47                     <artifactId>spring-boot-starter-test</artifactId>
48                     <scope>test</scope>
49                 </dependency>
50             </dependencies>
51 
52             <build>
53                 <plugins>
54                     <plugin>
55                         <groupId>org.springframework.boot</groupId>
56                         <artifactId>spring-boot-maven-plugin</artifactId>
57                         <configuration>
58                             <mainClass>com.example.App</mainClass>
59                             <layout>JAR</layout>
60                         </configuration>
61                         <executions>
62                             <execution>
63                                 <goals>
64                                     <goal>repackage</goal>
65                                 </goals>
66                             </execution>
67                         </executions>
68                     </plugin>
69                 </plugins>
70             </build>
71 
72         </project>


    3) 创建 src/main/resources/application.yml 文件

        server:
            port: 5001  # 端口号
        spring:
            application:
                name: alibaba-service-consumer   # 服务名
            cloud:
                nacos:
                    discovery:
                        server-addr: 127.0.0.1:8848  # Nacos server 的地址
        service:
            url: http://alibaba-service-provider    # 服务提供者的服务名


    4) 创建 src/main/java/com/example/config/RestTemplateConfig.java 文件

 1         package com.example.config;
 2 
 3         import org.springframework.cloud.client.loadbalancer.LoadBalanced;
 4         import org.springframework.context.annotation.Bean;
 5         import org.springframework.context.annotation.Configuration;
 6         import org.springframework.web.client.RestTemplate;
 7 
 8         @Configuration
 9         public class RestTemplateConfig {
10             @Bean
11             @LoadBalanced   // 开启负载均衡功能
12             public RestTemplate getRestTemplate() {
13                 return new RestTemplate();
14             }
15         }


    5) 创建 src/main/java/com/example/controller/IndexController.java 文件

 1         package com.example.controller;
 2 
 3         import org.springframework.beans.factory.annotation.Autowired;
 4         import org.springframework.beans.factory.annotation.Value;
 5         import org.springframework.web.bind.annotation.GetMapping;
 6         import org.springframework.web.bind.annotation.PathVariable;
 7         import org.springframework.web.bind.annotation.RestController;
 8         import org.springframework.web.client.RestTemplate;
 9 
10         @RestController
11         public class IndexController {
12             @Autowired
13             private RestTemplate restTemplate;
14             @Value("${service.url}")
15             private String serverURL; //服务提供者的服务名
16 
17             @GetMapping("/consumer/service/{id}")
18             public String getConsumerService(@PathVariable("id") Long id) {
19                 return restTemplate.getForObject(serverURL + "/service/" + id, String.class);
20             }
21         }


    6) 修改 src/main/java/com/example/App.java 文件

 1         package com.example;
 2 
 3         import org.springframework.boot.SpringApplication;
 4         import org.springframework.boot.autoconfigure.SpringBootApplication;
 5         import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 6 
 7         @SpringBootApplication
 8         @EnableDiscoveryClient  // 开启服务发现功能
 9         public class App {
10             public static void main(String[] args) {
11                 SpringApplication.run(App.class, args);
12             }
13         }


    7) 运行
    
        启动 Consumer 模块,浏览器访问 “http://localhost:5001/consumer/service/3”,结果如下。

            Nacos - Service Provider
            Service Name: alibaba-service-provider
            Port: 8001
            Id: 3


posted @ 2022-07-16 21:12  垄山小站  阅读(215)  评论(0编辑  收藏  举报