SYSTEM
服务注册与发现
src/content/notes/system/服务注册.md 服务注册
Eureka
基本介绍
Spring Cloud 封装了 Netflix 公司开发的 Eureka 模块来实现服务治理。Eureka 采用了 CS(Client-Server) 的设计架构,Eureka Server 是服务注册中心,系统中的其他微服务使用 Eureka 的客户端连接到 Eureka Server 并维持心跳连接

-
Eureka Server 提供服务注册服务:各个微服务节点通过配置启动后,会在 EurekaServer 中进行注册,EurekaServer 中的服务注册表中将会存储所有可用服务节点的信息,并且具有可视化界面
-
Eureka Client 通过注册中心进行访问:用于简化 Eureka Server的交互,客户端也具备一个内置的、使用轮询 (round-robin) 负载算法的负载均衡器。在应用启动后将会向 Eureka Server 发送心跳(默认周期为30秒),如果 Eureka Server 在多个心跳周期内没有接收到某个节点的心跳,将会从服务注册表中把这个服务节点移除(默认 90 秒)
服务端
服务器端主启动类增加 @EnableEurekaServer 注解,指定该模块作为 Eureka 注册中心的服务器
构建流程如下:
-
主启动类
@SpringBootApplication @EnableEurekaServer // 表示当前是Eureka的服务注册中心 public class EurekaMain7001 { public static void main(String[] args) { SpringApplication.run(EurekaMain7001.class, args); } } -
修改 pom 文件
1.x: server跟client合在一起 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> 2.x: server跟client分开 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> -
修改 application.yml 文件
server: port: 7001 eureka: instance: hostname: localhost # eureka服务端的实例名称 client: # false表示不向注册中心注册自己。 register-with-eureka: false # false表示自己端就是注册中心,职责就是维护服务实例,并不需要去检索服务 fetch-registry: false service-url: # 设置与 Eureka Server 交互的地址查询服务和注册服务都需要依赖这个地址。 defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ -
游览器访问 http://localhost:7001
客户端
生产者
服务器端主启动类需要增加 @EnableEurekaClient 注解,表示这是一个 Eureka 客户端,要注册进 EurekaServer 中
-
主启动类:PaymentMain8001
@SpringBootApplication @EnableEurekaClient public class PaymentMain8001 { public static void main(String[] args) { SpringApplication.run(PaymentMain8001.class, args); } } -
修改 pom 文件:添加一个 Eureka-Client 依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> -
写 yml 文件
server: port: 8001 eureka: client: # 表示将自己注册进EurekaServer默认为true register-with-eureka: true # 表示可以从Eureka抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡 fetch-registry: true service-url: defaultZone: http://localhost:7001/eureka instance: instance-id: payment8001 # 只暴露服务名,不带有主机名 prefer-ip-address: true # 访问信息有 IP 信息提示(鼠标停留在服务名称上时) -
游览器访问 http://localhost:7001
消费者
-
主启动类:PaymentMain8001
@SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient public class PaymentMain8001 { public static void main(String[] args) { SpringApplication.run(PaymentMain8001.class, args); } } -
pom 文件同生产者
-
写 yml 文件
server: port: 80 # 微服务名称 spring: application: name: cloud-order-service eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:7001/eureka -
浏览器访问 http://localhost:7001

集群构建
服务端
Server 端高可用集群原理:实现负载均衡和故障容错,互相注册,相互守望

多台 Eureka 服务器,每一台 Eureka 服务器需要有自己的主机名,同时各服务器需要相互注册
-
Eureka1:
server: port: 7001 eureka: instance: hostname: eureka7001.com client: register-with-eureka: false fetch-registry: false service-url: # 设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址。 # 单机就是自己 # defaultZone: http://eureka7001.com:7001/eureka/ # 集群指向其他eureka #defaultZone: http://eureka7002.com:7002/eureka/ # 写成这样可以直接通过可视化页面跳转到7002 defaultZone: http://eureka7002.com:7002/ -
Eureka2:
server: port: 7002 eureka: instance: hostname: eureka7002.com client: register-with-eureka: false fetch-registry: false service-url: #写成这样可以直接通过可视化页面跳转到7001 defaultZone: http://eureka7001.com:7001/ -
主启动类:
@SpringBootApplication @EnableEurekaServer public class EurekaMain7002 { public static void main(String[] args) { SpringApplication.run(EurekaMain7002.class, args); } } -
访问 http://eureka7001.com:7001 和 http://eureka7002.com:7002:

-
RPC 调用:controller.OrderController
@RestController @Slf4j public class OrderController { public static final String PAYMENT_URL = "http://localhost:8001"; @Autowired private RestTemplate restTemplate; // CommonResult 是一个公共的返回类型 @GetMapping("/consumer/payment/get/{id}") public CommonResult<Payment> getPayment(@PathVariable("id") long id) { // 返回对象为响应体中数据转化成的对象,基本上可以理解为JSON return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class); } }
生产者
构建 PaymentMain8001 的服务集群
-
主启动类
@SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient public class PaymentMain8002 { public static void main(String[] args) { SpringApplication.run(PaymentMain8002.class, args); } } -
写 yml 文件:端口修改,并且 spring.application.name 均为 cloud-payment-service
server: port: 8002 spring: application: name: cloud-payment-service eureka: client: # 表示将自己注册进EurekaServer默认为true register-with-eureka: true # 表示可以从Eureka抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡 fetch-registry: true service-url: defaultZone: http://localhost:7001/eureka
负载均衡
消费者端的 Controller
// public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://localhost:8002";
由于已经建立了生产者集群,所以可以进行负载均衡的操作:
-
Controller:只修改 PAYMENT_URL 会报错,因为 CLOUD-PAYMENT-SERVICE 对应多个微服务,需要规则来判断调用哪个端口
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE"; -
使用 @LoadBlanced 注解赋予 RestTemplate 负载均衡的能力,增加 config.ApplicationContextConfig 文件:
@Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); } }
服务发现
服务发现:对于注册进 Eureka 里面的微服务,可以通过服务发现来获得该服务的信息
-
主启动类增加注解 @EnableDiscoveryClient:
@SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient public class PaymentMain8001 { public static void main(String[] args) { SpringApplication.run(PaymentMain8001.class, args); } } -
修改生产者的 Controller
@RestController @Slf4j public class PaymentController { @Autowired private DiscoveryClient discoveryClient; @GetMapping(value = "/payment/discovery") public Object discovery() { List<String> services = discoveryClient.getServices(); for (String service : services) { log.info("**** element:" + service); } List<ServiceInstance> instances = discoveryClient.getInstances("PAYMENT-SERVICE"); for (ServiceInstance instance : instances) { log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort()); } return this.discoveryClient; } }
自我保护
保护模式用于客户端和 EurekaServer 之间存在网络分区场景下的保护,一旦进入保护模式 EurekaServer 将会尝试保护其服务注册表中的信息,不在删除服务注册表中的数据,属于 CAP 里面的 AP 思想(可用性和分区容错性)

如果一定时间内丢失大量该微服务的实例,这时 Eureka 就会开启自我保护机制,不会剔除该服务。 因为这个现象可能是因为网络暂时不通,出现了 Eureka 的假死、拥堵、卡顿,客户端恢复后还能正常发送心跳
禁止自我保护:
-
Server:
eureka: server: # 关闭自我保护机制,不可用的服务直接删除 enable-self-preservation: false eviction-interval-timer-in-ms: 2000 -
Client:
eureka: instance: # Eureka客户端向服务端发送心跳的时间间隔默认30秒 lease-renewal-interval-in-seconds: 1 # Eureka服务端在收到最后一次心跳后,90s没有收到心跳,剔除服务 lease-expiration-duration-in-seconds: 2
Consul
基本介绍
Consul 是开源的分布式服务发现和配置管理系统,采用 Go 语言开发,官网:https://developer.hashicorp.com/consul
- 提供了微服务系统中心的服务治理,配置中心,控制总线等功能
- 基于 Raft 协议,支持健康检查,同时支持 HTTP 和 DNS 协议支持跨数据中心的 WAN 集群
- 提供图形界面
下载 Consul 后,运行指令:consul -version
D:\Program Files\Java>consul -version
Consul v1.15.1
Revision 7c04b6a0
Build Date 2023-03-07T20:35:33Z
Protocol 2 spoken by default, understands 2 to 3 (.....)
启动命令:
consul agent -dev
访问浏览器:http://localhost:8500/
中文文档:https://www.springcloud.cc/spring-cloud-consul.html
基本使用
无需 Server 端代码的编写
生产者:
-
引入 pom 依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> -
application.yml:
###consul 服务端口号 server: port: 8006 spring: application: name: consul-provider-payment ####consul注册中心地址 cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name} -
主启动类:
@SpringBootApplication @EnableDiscoveryClient public class PaymentMain8006 { public static void main(String[] args) { SpringApplication.run(PaymentMain8006.class, args); } }
消费者:
-
application.yml:
###consul服务端口号 server: port: 80 spring: application: name: cloud-consumer-order ####consul注册中心地址 cloud: consul: host: localhost port: 8500 discovery: #hostname: 127.0.0.1 service-name: ${spring.application.name} -
主启动类:同生产者
-
配置类:
@Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); } } -
业务类 Controller:
@RestController @Slf4j public class OrderConsulController { public static final String INVOKE_URL = "http://cloud-provider-pament"; @Resource private RestTemplate restTemplate; @GetMapping("/consumer/payment/consul") public String paymentInfo() { return restTemplate.getForObject(INVOKE_URL, String.class); } }