LarryDpk
发布于 2022-01-11 / 1798 阅读
0

Spring Cloud Service Discovery with Netflix Eureka

Introduction

Netflix Eureka is one of the most popular Serice Discovery Framework for micro service system. It's very easy to use based on Spring Cloud. With all the clients registering to the Eureka server, they can talk to each other without hard-coding the hostname and port.

I will show how to implement the Eureka server and client.

Eureka Server

Add maven dependency into your project:

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

And the annotation @EnableEurekaServer to the Spring Boot main class to enable it:

package com.pkslow.cloud.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServer {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer.class, args);
    }
}

Configure the port for the server:

server:
  port: 8761
eureka:
  client:
    fetch-registry: false
    register-with-eureka: false

Start up the Eureka Spring Boot application and open the link: http://localhost:8761/

We can see the server info, but no any instances registered with Eureka.

Eureka Client

The clients need to register to Eureka server to be dicovered.

Add dependencies into maven pom:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

Add annotation @EnableEurekaClient:

package com.pkslow.cloud.rest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class RestService {
    public static void main(String[] args) {
        SpringApplication.run(RestService.class, args);
    }
}

Configure the server link on client side:

spring.application.name=rest-service
server.port=8081
pkslow.admin=larry|18|admin@pkslow.com
eureka.client.service-url.defaultZone: http://localhost:8761/eureka
eureka.instance.prefer-ip-address=true
management.endpoints.web.exposure.include=*

Start up the client and refresh the Eureka Server page again:

We can see the client instances now.

Code

Code on GitHub: https://github.com/LarryDpk/pkslow-samples


References:

Introduction to Spring Cloud Netflix Eureka

Eureka Server