第二篇:SpringCloud 构建微服务系统之服务注册和发现(nacos)

绝地灬酷狼 2022-04-02 10:48 357阅读 0赞

上一篇我们学习了一下consulSpringCloud中的使用。今天要给大家介绍的阿里巴巴中间件团队出品的Nacos来作为新一代的服务管理中间件。
首先学习Nacos之前,我们应该看看Nacos的官网,对它有一个初步的认识。

1. Nacos 官网 (https://nacos.io)

在这里插入图片描述

2 Nacos简介

Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现服务配置服务元数据流量管理

Nacos帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以服务为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施

3.Nocos基本架构及概念

在这里插入图片描述

  • 服务 (Service)

服务是指一个或一组软件功能(例如特定信息的检索或一组操作的执行),其目的是不同的客户端可以为不同的目的重用(例如通过跨进程的网络调用)。Nacos 支持主流的服务生态,如 Kubernetes Service、gRPC|Dubbo RPC Service 或者 Spring Cloud RESTful Service.

  • 服务注册中心 (Service Registry)

服务注册中心,它是服务,其实例及元数据的数据库。服务实例在启动时注册到服务注册表,并在关闭时注销。服务和路由器的客户端查询服务注册表以查找服务的可用实例。服务注册中心可能会调用服务实例的健康检查 API 来验证它是否能够处理请求。

  • 服务元数据 (Service Metadata)

服务元数据是指包括服务端点(endpoints)、服务标签、服务版本号、服务实例权重、路由规则、安全策略等描述服务的数据

  • 服务提供方 (Service Provider)

是指提供可复用和可调用服务的应用方

  • 服务消费方 (Service Consumer)

是指会发起对某个服务调用的应用方

  • 配置 (Configuration)

在系统开发过程中通常会将一些需要变更的参数、变量等从代码中分离出来独立管理,以独立的配置文件的形式存在。目的是让静态的系统工件或者交付物(如 WAR,JAR 包等)更好地和实际的物理运行环境进行适配。配置管理一般包含在系统部署的过程中,由系统管理员或者运维人员完成这个步骤。配置变更是调整系统运行时的行为的有效手段之一。

  • 配置管理 (Configuration Management)

在数据中心中,系统中所有配置的编辑、存储、分发、变更管理、历史版本管理、变更审计等所有与配置相关的活动统称为配置管理。

  • 名字服务 (Naming Service)

提供分布式系统中所有对象(Object)、实体(Entity)的“名字”到关联的元数据之间的映射管理服务,例如 ServiceName -> Endpoints Info, Distributed Lock Name -> Lock Owner/Status Info, DNS Domain Name -> IP List, 服务发现和 DNS 就是名字服务的2大场景。

  • 配置服务 (Configuration Service)

在服务或者应用运行过程中,提供动态配置或者元数据以及配置管理的服务提供者

4. Nocos 安装与启动

4.1.预备环境准备

Nacos 依赖 Java环境来运行。如果您是从代码开始构建并运行Nacos,还需要为此配置Maven环境,请确保是在以下版本环境中安装使用:

64 bit OS,支持 Linux/Unix/Mac/Windows,推荐选用Linux/Unix/Mac
64 bit JDK 1.8+;下载 & 配置。
Maven 3.2.x+;下载 & 配置。

4.2.下载源码或者安装包

你可以通过源码和发行包两种方式来获取 Nacos

从 Github 上下载源码方式

  1. git clone https://github.com/alibaba/nacos.git
  2. cd nacos/
  3. mvn -Prelease-nacos clean install -U
  4. ls -al distribution/target/
  5. // change the $version to your actual path
  6. cd distribution/target/nacos-server-$version/nacos/bin

下载编译后压缩包方式
您可以从 最新稳定版本 下载 nacos-server-$version.zip 包。

  1. unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz
  2. cd nacos/bin

4.3.启动服务器

Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式):

  1. sh startup.sh -m standalone

Windows启动命令:

  1. cmd startup.cmd

或者双击startup.cmd运行文件。
在这里插入图片描述

启动成功之后,在浏览器打开 http://localhost:8848/nacos/

在这里插入图片描述
这样的一个控制台就启动成功了。

注意:我们今天主要是要学习nacos作为服务注册中心的案例。

5. 服务注册与发现

5.1服务注册

  1. curl -X PUT 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=nacos.naming.serviceName&ip=20.18.7.10&port=8080'

5.2服务发现

  1. curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/instances?serviceName=nacos.naming.serviceName'

6. Nacos 服务提供者

6.1创建一个项目:spring-cloud-nacos-provider

引入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <modelVersion>4.0.0</modelVersion>
  4. <parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>2.1.1.RELEASE</version>
  8. <relativePath/> <!-- lookup parent from repository -->
  9. </parent>
  10. <groupId>com.lidong</groupId>
  11. <artifactId>spring-cloud-nacos-producer</artifactId>
  12. <version>1.0.0</version>
  13. <name>spring-cloud-nacos-producer</name>
  14. <description>Demo project for Spring Boot</description>
  15. <properties>
  16. <java.version>1.8</java.version>
  17. <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-actuator</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>com.alibaba.cloud</groupId>
  30. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  31. <version>2.1.0.RELEASE</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-actuator</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-web</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter-test</artifactId>
  44. <scope>test</scope>
  45. </dependency>
  46. </dependencies>
  47. <dependencyManagement>
  48. <dependencies>
  49. <dependency>
  50. <groupId>org.springframework.cloud</groupId>
  51. <artifactId>spring-cloud-dependencies</artifactId>
  52. <version>${spring-cloud.version}</version>
  53. <type>pom</type>
  54. <scope>import</scope>
  55. </dependency>
  56. </dependencies>
  57. </dependencyManagement>
  58. <build>
  59. <plugins>
  60. <plugin>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-maven-plugin</artifactId>
  63. </plugin>
  64. </plugins>
  65. </build>
  66. <repositories>
  67. <repository>
  68. <id>spring-milestones</id>
  69. <name>Spring Milestones</name>
  70. <url>https://repo.spring.io/milestone</url>
  71. </repository>
  72. </repositories>
  73. </project>

对配置文件做一个简单的介绍,我们使用的是最新版的springboot2.1.1,springcloud.Greenwich.RC2版本。
其中:

  1. spring-boot-starter-actuator 健康检查依赖于此包。
  2. spring-cloud-starter-alibaba-nacos-discovery Spring Cloud nacos 的服务发现支持。

6.2 提供者添加配置(application.yml)

  1. server:
  2. port: 9005 #提供者的端口
  3. spring:
  4. application:
  5. name: spring-cloud-nacos-producer
  6. cloud:
  7. nacos:
  8. discovery:
  9. server-addr: 127.0.0.1:8848
  10. management:
  11. endpoints:
  12. web:
  13. exposure:
  14. include: '*'

nacos的地址和端口号默认是127.0.0.1:8848 ,如果没有配置hosts,默认的地址localhost,nacos服务会占用8848端口
server.port :9005 服务的提供者的端口
spring.application.name 是指注册到 nacos 的服务名称,后期客户端会根据这个名称来进行服务调用。
spring.application.cloud.nacos.discovery.server-addr: 127.0.0.1:8848

6.3 修改启动类

添加 @EnableDiscoveryClient 注解,开启服务发现支持。

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

6.4新建服务

新建 NacosProducerController,提供 sayHello 接口, 返回一个hello—>字符串。

  1. package com.lidong.provider.service;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. /** * 创建服务 */
  5. @RestController
  6. public class NacosProducerController {
  7. @Value("${server.port}")
  8. private Integer port;
  9. /** * 服务接口 * @param name * @return */
  10. @RequestMapping("/hello")
  11. public String sayHello(@RequestParam("name")String name) {
  12. return "hello ---> "+name+" port -->"+port;
  13. }
  14. }

启动项目:

  1. Wed Dec 26 11:55:40 CST 2018 sun.misc.Launcher$AppClassLoader@18b4aac2 JM.Log:INFO Init JM logger with Slf4jLoggerFactory success, sun.misc.Launcher$AppClassLoader@18b4aac2
  2. Wed Dec 26 11:55:40 CST 2018 sun.misc.Launcher$AppClassLoader@18b4aac2 JM.Log:INFO Log root path: C:\Users\vip\logs\
  3. Wed Dec 26 11:55:40 CST 2018 sun.misc.Launcher$AppClassLoader@18b4aac2 JM.Log:INFO Set nacos log path: C:\Users\vip\logs\nacos
  4. 2018-12-26 11:55:40.842 INFO 22252 --- [ main] o.s.c.a.n.registry.NacosServiceRegistry : nacos registry, spring-cloud-nacos-producer 192.168.10.116:9005 register finished

服务提供者发布成功。
这时候,我们在控制台会发现服务列表中有一个名字为spring-cloud-nacos-producer的服务
在这里插入图片描述

点击详情会发现服务的详细信息

在这里插入图片描述

7. Nacos 服务消费者

7.1创建一个项目:spring-cloud-nacos-consumer

引入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <modelVersion>4.0.0</modelVersion>
  4. <parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>2.1.1.RELEASE</version>
  8. <relativePath/> <!-- lookup parent from repository -->
  9. </parent>
  10. <groupId>com.lidong</groupId>
  11. <artifactId>spring-cloud-nacos--consumer</artifactId>
  12. <version>0.0.1-SNAPSHOT</version>
  13. <name>spring-cloud-nacos--consumer</name>
  14. <description>Demo project for Spring Boot</description>
  15. <properties>
  16. <java.version>1.8</java.version>
  17. <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-actuator</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>com.alibaba.cloud</groupId>
  26. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  27. <version>2.1.0.RELEASE</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-web</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.cloud</groupId>
  40. <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.cloud</groupId>
  44. <artifactId>spring-cloud-starter-openfeign</artifactId>
  45. </dependency>
  46. </dependencies>
  47. <dependencyManagement>
  48. <dependencies>
  49. <dependency>
  50. <groupId>org.springframework.cloud</groupId>
  51. <artifactId>spring-cloud-dependencies</artifactId>
  52. <version>${spring-cloud.version}</version>
  53. <type>pom</type>
  54. <scope>import</scope>
  55. </dependency>
  56. </dependencies>
  57. </dependencyManagement>
  58. <build>
  59. <plugins>
  60. <plugin>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-maven-plugin</artifactId>
  63. </plugin>
  64. </plugins>
  65. </build>
  66. <repositories>
  67. <repository>
  68. <id>spring-milestones</id>
  69. <name>Spring Milestones</name>
  70. <url>https://repo.spring.io/milestone</url>
  71. </repository>
  72. </repositories>
  73. </project>

7.2 消费者添加配置(application.yml)

  1. server:
  2. port: 9006 #提供者的端口
  3. spring:
  4. application:
  5. name: spring-cloud-nacos-consumer
  6. cloud:
  7. nacos:
  8. discovery:
  9. server-addr: 127.0.0.1:8848
  10. management:
  11. endpoints:
  12. web:
  13. exposure:
  14. include: '*'

nacos的地址和端口号默认是 127.0.0.1:8848 ,如果没有配置hosts,默认的地址localhost,nacos服务会占用8848接口
server.port :9006 服务的消费者的端口
spring.application.cloud.nacos.discovery.server-addr: 127.0.0.1:8848

7.3配置启动类

  1. package com.lidong.consumer;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.boot.web.client.RestTemplateBuilder;
  6. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  7. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.web.client.RestTemplate;
  10. @SpringBootApplication
  11. @EnableDiscoveryClient
  12. public class SpringCloudNacosConsumerApplication {
  13. @Autowired
  14. private RestTemplateBuilder builder;
  15. @Bean
  16. @LoadBalanced // 添加负载均衡支持,很简单,只需要在RestTemplate上添加@LoadBalanced注解,那么RestTemplate即具有负载均衡的功能,如果不加@LoadBalanced注解的话,会报java.net.UnknownHostException:springboot-h2异常,此时无法通过注册到Nacos Server上的服务名来调用服务,因为RestTemplate是无法从服务名映射到ip:port的,映射的功能是由LoadBalancerClient来实现的。
  17. public RestTemplate restTemplate() {
  18. return builder.build();
  19. }
  20. public static void main(String[] args) {
  21. SpringApplication.run(SpringCloudNacosConsumerApplication.class, args);
  22. }
  23. }

7.4创建消费服务

  1. package com.lidong.consumer.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.cloud.client.ServiceInstance;
  4. import org.springframework.cloud.client.discovery.DiscoveryClient;
  5. import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestParam;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import org.springframework.web.client.RestTemplate;
  10. /** * 创建服务的消费者 */
  11. @RestController
  12. public class ConsumerController {
  13. private static final String SERVICE_NAME = "spring-cloud-nacos-producer";
  14. @Autowired
  15. private DiscoveryClient discoveryClient;
  16. /** * 获取所有服务 */
  17. @RequestMapping("/services")
  18. public Object services() {
  19. return discoveryClient.getInstances(SERVICE_NAME);
  20. }
  21. /** * 消费服务 */
  22. @RequestMapping("/callSayHello")
  23. public String services(@RequestParam("name") String name) {
  24. ServiceInstance serviceInstance = (ServiceInstance) discoveryClient.getInstances(SERVICE_NAME);
  25. String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class);
  26. System.out.println(callServiceResult);
  27. return callServiceResult;
  28. }
  29. }

http://localhost:9006/services

获取服务列表的结果

  1. [{ "serviceId":"spring-cloud-nacos-producer","host":"192.168.10.116","port":9005,"secure":false,"metadata":{ "cluster":"DEFAULT","instanceId":"192.168.10.116#9005#DEFAULT#spring-cloud-nacos-producer","healthy":"true","weight":"1.0"},"uri":"http://192.168.10.116:9005","scheme":null,"instanceId":null}]

测试请求的url
http://localhost:9006/callSayHello?name=9006
消费的结果

  1. hello ---> 9006 port -->9005

备注:spring.cloud.nacos配置说明

配置项|key|默认值|说明

更多配置项


























































































配置项 key 默认值 说明
服务端地址 spring.cloud.nacos.discovery.server-addr
服务名 spring.cloud.nacos.discovery.service spring.application.name
权重 spring.cloud.nacos.discovery.weight 1 取值范围 1 到 100,数值越大,权重越大
网卡名 spring.cloud.nacos.discovery.network-interface 当IP未配置时,注册的IP为此网卡所对应的IP地址,如果此项也未配置,则默认取第一块网卡的地址
注册的IP地址 spring.cloud.nacos.discovery.ip 优先级最高
注册的端口 spring.cloud.nacos.discovery.port -1 默认情况下不用配置,会自动探测
命名空间 spring.cloud.nacos.discovery.namespace 常用场景之一是不同环境的注册的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等。
AccessKey spring.cloud.nacos.discovery.access-key
SecretKey spring.cloud.nacos.discovery.secret-key
Metadata spring.cloud.nacos.discovery.metadata 使用Map格式配置
日志文件名 spring.cloud.nacos.discovery.log-name
接入点 spring.cloud.nacos.discovery.endpoint UTF-8 地域的某个服务的入口域名,通过此域名可以动态地拿到服务端地址
是否集成Ribbon ribbon.nacos.enabled true

到这里Nacos作为注册中心来注册服务和发现服务的流程就已经完成。这只是个简单入门,深入学习请关照nacos官方信息。

源码地址
https://github.com/lidong1665/spring-cloud-learning-example

发表评论

表情:
评论列表 (有 0 条评论,357人围观)

还没有评论,来说两句吧...

相关阅读