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

Running Eureka on the server side

Running the Eureka Server within a Spring Boot application is not a difficult task. Let's take a look at how this can be done:

  1. First, the right dependency has to be included to our project. Obviously, we will use a starter for that:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
  1. Eureka Server should also be enabled on the main application class:
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {

public static void main(String[] args) {
new SpringApplicationBuilder(DiscoveryApplication.class).web(true).run(args);
}

}
  1. It is interesting that together with the server starter, client's dependencies are also included. They can be useful for us, but only when launching Eureka in high availability mode with peer-to-peer communication between discovery instances. When running a standalone instance, it doesn't really get us anywhere except printing some errors in the logs during startup. We can either exclude spring-cloud-netflix-eureka-client from the starter dependencies or disable discovery client using configuration properties. I prefer the second choice, and also on this occasion, I changed the default server port to something other than 8080. Here's the fragment of the application.yml file:
server: 
port: ${PORT:8761}
eureka:
client:
registerWithEureka: false
fetchRegistry: false
  1. After completing the preceding steps, we can finally launch our first Spring Cloud application. Just run the main class from your IDE or build project with Maven; run it using the java -jar command and wait for the log line, Started Eureka Server. It's up. A simple UI dashboard is available as a home page at http://localhost:8761 and HTTP API methods may be called with the /eureka/* path. The Eureka dashboard does not provide many features; in fact, it is mostly used for checking out the list of registered services. This could be found out by calling the REST API http://localhost:8761/eureka/apps endpoint.

So, to conclude, we know how to run a Eureka standalone server with Spring Boot and how to check the list of registered microservices using the UI console and HTTP methods. But we still don't have any service that is able to register itself in discovery, and it's time to change that. An example application with a discovery server and client implementation is available on GitHub (https://github.com/piomin/sample-spring-cloud-netflix.git) in the master branch.