第5 章 Consul服务注册与发现
1、为什么要引入服务注册中心
public static final String PaymentSrv_URL = "http://localhost:8001";//先写死,硬编码
微服务所在的IP地址和端口号硬编码到订单微服务中,会存在非常多的问题
(1)如果订单微服务和支付微服务的IP地址或者端口号发生了变化,则支付微服务将变得不可用,需要同步修改订单微服务中调用支付微服务的IP地址和端口号。
(2)如果系统中提供了多个订单微服务和支付微服务,则无法实现微服务的负载均衡功能。
(3)如果系统需要支持更高的并发,需要部署更多的订单微服务和支付微服务,硬编码订单微服务则后续的维护会变得异常复杂。
所以,在微服务开发的过程中,需要引入服务治理功能,实现微服务之间的动态注册与发现。
2、为什么不再使用传统老牌的Eureka
- Eureka停更进维
- Eureka对初学者不友好
- 自我保护机制
- 注册中心独立且和微服务功能解耦
- 注册中心Eureka也是作为一个微服务且需要程序员自己开发部署
- 目前主流服务中心,希望单独隔离出来而不是作为一个独立微服务嵌入到系统中
- 阿里巴巴Nacos的崛起
- Service discovery and configuration management
- Service discovery and configuration management
3、consul简介
3.1 是什么
3.1.1 官网
consul官网地址 https://www.consul.io/
3.1.2 What is Consul
https://developer.hashicorp.com/consul/docs/intro
3.1.3 spring consul
https://docs.spring.io/spring-cloud-consul/docs/current/reference/html/
3.2 能干嘛
- 服务发现
提供HTTP和DNS两种发现方式。 - 健康监测
支持多种方式,HTTP、TCP、Docker、Shel脚本定制化监控 - KV存储
Key、Value的存储方式 - 多数据中心
Consu支持多数据中心 - 可视化Web界面
3.3 去哪下
https://developer.hashicorp.com/consul/downloads
3.4 怎么玩
- Service discovery and configuration management
- https://docs.spring.io/spring-cloud-consul/docs/current/reference/html/
4、安装并运行consul
4.1官网下载
https://developer.hashicorp.com/consul/downloads
4.2 安装
下载完成后只有一个consul.exe文件,对应全路径下查看版本号信息
4.3 使用开发模式启动
- consul agent -dev安装路径下执行
- 通过以下地址可以访问Consul的首页:http://localhost:8500
- 结果页面
5、服务注册与发现
5.1服务提供者8001
支付服务provider8001注册进consul
5.1.1 改pom
配置来源
https://docs.spring.io/spring-cloud-consul/reference/quickstart.html
<!--SpringCloud consul discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
5.1.2 改yml
spring:
cloud:
consul:
host: localhost
port: 8500
discove