下面是将consul 作为注册中心,而非 eureka ,我将eureka 做注册中心的代码放到了码云上:
springCloud01: springCloud01-20211225 练习springCloudhttps://gitee.com/vegetarian/spring-cloud01.git
一,案例准备
将一个基本的微服务案例创建出来,不使用任何注册中心,我们一步步搭建。
springCloud_consul: springCloud_consulhttps://gitee.com/vegetarian/spring-cloud_consul.git
二,修改微服务的pom 文件
修改
每个微服务
的pom
文件,添加
SpringCloud
提供的基于
Consul
的依赖
<!--SpringCloud提供的基于Consul的服务发现-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--actuator用于心跳检查-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
其中 spring
-
cloud
-
starter
-
consul
-
discovery
是
SpringCloud
提供的对
consul
支持的相关依赖。
spring-
boot
-
starter
-
actuator
适用于完成心跳检测响应的相关依赖。
三,修改配置文件
修改每个微服务的application.yml
配置文件,添加
consul
服务发现的相关配置信息
spring:
...省略
cloud:
consul: #consul相关配置
host: 192.168.74.101 #ConsulServer请求地址
port: 8500 #ConsulServer端口
discovery:
#是否注册
register: true
#实例ID
instance-id: ${spring.application.name}-1
#服务实例名称
service-name: ${spring.application.name}
#服务实例端口
port: ${server.port}
#健康检查路径
healthCheckPath: /actuator/health
#健康检查时间间隔
healthCheckInterval: 15s
#开启ip地址注册
prefer-ip-address: true
#实例的请求ip
ip-address: ${spring.cloud.client.ip-address}
server:
port: 9001
spring:
application:
name: service-product
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springclouddemo?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: root
jpa:
database: MySQL
show-sql: true
open-in-view: true
cloud:
consul:
host: 127.0.0.1 #consulServer请求地址
port: 8500 #consulServer 端口
discovery:
register: true #是否注册
instance-id: ${spring.application.name}-1 #实例id
service-name: ${spring.application.name} #服务器实例名称
port: ${server.port} #服务实例端口
health-check-interval: 15s # 健康检查时间间隔
health-check-path: /actuator/health #健康检查路径
prefer-ip-address: true # 开启ip 地址注册
ip-address: ${spring.cloud.client.ip-address} #实例的请求ip
- spring.cloud.consul 中添加consul的相关配置
- host:表示Consul的Server的请求地址
- port:表示Consul的Server的端口
- discovery:服务注册与发现的相关配置
- instance-id : 实例的唯一id(推荐必填),spring cloud官网文档的推荐,为了保证生成一个唯一的id ,也可以换${spring.application.name}:${spring.cloud.client.ipAddress}
- prefer-ip-address:开启ip地址注册
- ip-address:当前微服务的请求ip
配置好服务提供者和服务消费者后,重新启动服务提供者和服务消费者,查看consul可视化页面