前言
在之前说到的Spring Cloud Config Client程序中都是通过spring.cloud.config.uri 指定Config Server的地址。这种方式Spring Cloud称之为“Config First Bootstrap”。除此之外,还支持一种服务发现的方式,Spring Cloud称之为“Discovery First Bootstrap”。本文将说明如何通过Eureka发现Config Server的服务。
Spring Cloud Config与Eureka配合使用
1.Config Server改造
既然是通过Eureka服务发现来帮助Config Client定位到Config Server,那么必须先将Config Server注册到Eureka上。
a.添加Eureka的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
b.在配置文件指定eureka的serviceUri
spring:
application:
name: cloud-config-server
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka
instance:
prefer-ip-address: true
注意需要指定Config Server的serviceId(spring.application.name),后面客户端从Eureka是根据serviceId查找Config Server的。
3.在Spring Boot主类增加@EnableEurekaClient
2.Config Client改造
a.添加Eureka的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
b.配置文件增加Config Server的服务发现配置
spring:
application:
name: cloud-config-client
cloud:
config:
name: cloud-config
profile: ${config.profile:dev}
discovery:
enabled: true
service-id: cloud-config-server
username: user
password: password123
上面的配置中,discovery.enabled指定是否启用服务发现,service-id指定服务id。
在上一节中说到有2种方式配置会用户名和密码,但如果使用服务发现的话,就只能使用这种单独指定username和password的形式了。
3.在Spring Boot主类增加@EnableEurekaClient
然后依次启动Eureka Server,Config Server和Config Client即可。