Eureka基本使用
环境:spring boot 2.2.2
配置服务端
必要依赖
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
yaml 配置文件
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/
启动类中开启 EurekaService 服务
启动模块,输入首页地址,出现如下界面表示安装成功
配置客户端
将客户端微服务入驻进服务端
依赖
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
yaml 配置文件
这里我把 Eureka 配置写在 mybatis 配置后面会报数据库连接错误,写在前面就没事了
eureka:
client:
#表示是否将自己注册进EurekaServer,默认为true。
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
# 这里是 [服务端地址/eureka]
defaultZone: http://localhost:7001/eureka
测试
打开服务端的地址,可以看到如图的内容。
新的微服务已经添加进去了,服务名字可以通过 spring.application.name 设置
搭建集群
- 这里因为使用本地环境,所以修改host模拟两台主机
host文件目录C:\Windows\System32\drivers\etc
-
创建两个模块作为两台主机,步骤与上述相同,只需修改yaml配置即可
-
7001主机yaml示例:
server: port: 7001 eureka: instance: hostname: eureka7001.com #eureka服务端的实例名称 client: register-with-eureka: false #false表示不向注册中心注册自己。 fetch-registry: false #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务 service-url: defaultZone: http://eureka7002.com:7002/eureka/ # 集群中其他主机 -
7002主机yaml示例:
server: port: 7002 eureka: instance: hostname: eureka7002.com #eureka服务端的实例名称 client: register-with-eureka: false fetch-registry: false service-url: defaultZone: http://eureka7001.com:7001/eureka/ # 集群中的其他主机可以看到,两台主机你关联我、我关联你
-
在浏览器中输入我们修改的host地址,即可看到效果
-
主机7001
-
主机7002
-
将客户端注册进集群
只需更改客户端的yaml即可
eureka:
client:
#表示是否将自己注册进EurekaServer默认为true。
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
#defaultZone: http://localhost:7001/eureka
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka # 集群版
启动项目时应注意启动顺序,先启动集群,在启动客户端