01-服务注册发现详解

张开发
2026/4/9 10:43:27 15 分钟阅读

分享文章

01-服务注册发现详解
Spring Cloud 服务注册发现详解一、知识概述服务注册与发现是微服务架构的核心基础设施,它解决了服务实例动态变化时的地址管理问题。Spring Cloud 提供了多种服务注册中心的支持,包括 Eureka、Nacos、Consul 等。服务注册发现的核心概念:服务注册:服务启动时向注册中心注册自己的地址服务发现:消费者从注册中心获取服务提供者的地址健康检查:注册中心定期检查服务实例的健康状态服务续约:服务实例定期向注册中心发送心跳理解服务注册发现的原理,是构建微服务架构的基础。二、知识点详细讲解2.1 服务注册发现架构服务提供者 注册中心 服务消费者 │ │ │ │──── 注册 ────────────│ │ │ │ │ │─── 心跳 ────────────│ │ │ │ │ │ │──── 发现 ────────────│ │ │ │ │ │───── 地址列表 ───────│ │ │ │ │──────────────────── 直接调用 ───────────────│2.2 注册中心对比特性EurekaNacosConsulCAPAPAP/CPCP健康检查心跳心跳/HTTP/TCPHTTP/TCP配置中心❌✅✅多数据中心❌✅✅一致性最终一致可选强一致2.3 Eureka 核心概念Eureka Server服务注册中心维护服务注册表提供服务发现接口Eureka Client服务提供者:注册服务、发送心跳服务消费者:获取服务列表、调用服务核心配置eureka:client:service-url:defaultZone:http://localhost:8761/eureka/register-with-eureka:true# 是否注册自己fetch-registry:true# 是否获取注册表instance:hostname:localhostlease-renewal-interval-in-seconds:30# 心跳间隔lease-expiration-duration-in-seconds:90# 过期时间2.4 Nacos 核心概念命名空间(Namespace)环境隔离(开发、测试、生产)租户隔离分组(Group)服务分组默认为 DEFAULT_GROUP服务(Service)服务名称服务实例列表实例(Instance)IP:Port权重健康状态元数据2.5 服务注册流程1. 服务启动 ↓ 2. 读取配置(注册中心地址、服务名称) ↓ 3. 向注册中心发送注册请求 ↓ 4. 注册中心保存服务实例信息 ↓ 5. 开始发送心跳 ↓ 6. 注册中心定期检查实例健康2.6 服务发现流程1. 服务启动 ↓ 2. 连接注册中心 ↓ 3. 订阅服务变更 ↓ 4. 获取服务实例列表 ↓ 5. 本地缓存服务列表 ↓ 6. 定期更新缓存 ↓ 7. 使用负载均衡选择实例三、代码示例3.1 Eureka Server 搭建!-- pom.xml --dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-eureka-server/artifactId/dependencyimportorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@SpringBootApplication@EnableEurekaServerpublicclassEurekaServerApplication{publicstaticvoidmain(String[]args){SpringApplication.run(EurekaServerApplication.class,args);}}# application.ymlserver:port:8761eureka:instance:hostname:localhostclient:register-with-eureka:false# 不注册自己fetch-registry:false# 不获取注册表service-url:defaultZone:http://${eureka.instance.hostname}:${server.port}/eureka/server:enable-self-preservation:false# 关闭自我保护(开发环境)eviction-interval-timer-in-ms:60000# 清理间隔spring:application:name:eureka-server3.2 Eureka Client 服务注册dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-eureka-client/artifactId/dependencyimportorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.netflix.eureka.EnableEurekaClient;importorg.springframework.web.bind.annotation.*;@SpringBootApplication@EnableEurekaClient@RestControllerpublicclassProviderApplication{publicstaticvoidmain(String[]args){SpringApplication.run(ProviderApplication.class,args);}@GetMapping("/hello")publicStringhello(){return"Hello from Provider!";}}# application.ymlserver:port:8081spring:application:

更多文章