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: GitHub - LarryDpk/pkslow-samples: samples for www.pkslow.com: Java, Spring Boot, Spring Cloud, Docker, Kubernetes, Cloud, Big Data

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值