Mastering Spring Cloud
上QQ阅读APP看书,第一时间看更新

Config Server discovery

To access that example on GitHub, you need to switch to the config_with_discovery branch. Here's the link:

https://github.com/piomin/sample-spring-cloud-netflix/tree/config_with_discovery.

The first change is related to the sample-service-discovery module. We don’t need the spring-cloud-starter-config dependency there. The simple configuration is not fetched from remote property sources, but set in bootstrap.yml. In contrast to the previous example, we launch a single standalone Eureka instance in order to simplify the exercise:

spring: 
application:
name: discovery-service

server:
port: ${PORT:8761}

eureka:
client:
registerWithEureka: false
fetchRegistry: false

By contrast, we should include the spring-cloud-starter-eureka dependency for the Config Server. Now, the full list of dependencies is shown in the following code. Moreover, a discovery client has to be enabled by declaring the @EnableDiscoveryClient annotation on the main class, and the Eureka Server address should be provided by setting the eureka.client.serviceUrl.defaultZone property to http://localhost:8761/eureka/ in the application.yml file:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

On the client application side, it is no longer needed to hold the address of the configuration server. The only thing that has to be set is the service ID, in case it is different than the Config Server. In accordance with the naming convention used for the services in the presented examples, that ID is config-server. It should be overridden with the spring.cloud.config.discovery.serviceId property. In order to allow discovery mechanism enable the discovery mechanism to fetch remote property sources from the configuration server, we should set spring.cloud.config.discovery.enabled=true:

spring: 
application:
name: client-service
cloud:
config:
discovery:
enabled: true
serviceId: config-server

Here's the screen with the Eureka dashboard, with one instance of the Config Server and three instances of client-service registered. Every instance of the client's Spring Boot application is the same as for the previous example and was launched with the --spring.profiles.active=zone[n] parameter, where n is the number of the zone. The only difference is that all of the client's service configuration files served by the Spring Cloud Config Server have the same connection address as the Eureka Server: