- Mastering Spring Cloud
- Piotr Minkowski
- 371字
- 2021-08-27 18:57:04
Enabling Eureka on the client side
As on the server side, there is only one dependency that has to be included to enable a Eureka Client for the application. So, first include the following starter to your project's dependencies:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
The example application does nothing more than communicate with the Eureka Server. It has to register itself and send metadata information such as host, port, health indicator URL, and home page. Eureka receives heartbeat messages from each instance belonging to a service. If the heartbeat isn't received after a configured period of time, the instance is removed from the registry. The second responsibility of discovery client is fetching data from the server, then caching it and periodically asking for changes. It can be enabled by annotating the main class with @EnableDiscoveryClient. Surprisingly, there is another way to activate this feature. You may use an annotation @EnableEurekaClient, especially if there are multiple implementations of discovery client within the classpath (Consul, Eureka, ZooKeeper). While @EnableDiscoveryClient lives in spring-cloud-commons, @EnableEurekaClient lives in spring-cloud-netflix and only works for Eureka. Here's the main class of the discovery client's application:
@SpringBootApplication
@EnableDiscoveryClient
public class ClientApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ClientApplication.class).web(true).run(args);
}
}
The discovery server address doesn't have to be provided in the client's configuration, because it is available on the default host and port. However, we could easily imagine that Eureka is not listening on its default 8761 port. The fragment of configuration file is visible below. The discovery server network address can be overridden with the EUREKA_URL parameter, as can the client's listening port with the PORT property. The name under which the application is registered in the discovery server is taken from the spring.application.name property:
spring:
application:
name: client-service
server:
port: ${PORT:8081}
eureka:
client:
serviceUrl:
defaultZone: ${EUREKA_URL:http://localhost:8761/eureka/}
Let's run two independent instances of our sample client application on localhost. To achieve that, the number of the listening port should be overridden for the instance on startup like this:
java -jar -DPORT=8081 target/sample-client-service-1.0-SNAPSHOT.jar
java -jar -DPORT=8082 target/sample-client-service-1.0-SNAPSHOT.jar
As you can see in the following screenshot, there are two instances of client-service registered with the hostname piomin and ports 8081 and 8082: