Spring Cloud Eureka

Keywords: Java Spring network

Eureka is responsible for service discovery in Spring Cloud. Service discovery needs to solve the problem of how to find the location of service provider in the network.

Server side

In the file menu of the Spring Tool Suite, click new Spring Starter Project.

Then add the @ EnableEurekaServer tag to the entry method.

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

@EnableEurekaServer
@SpringBootApplication
public class SpringcloudEurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudEurekaServerApplication.class, args);
    }
}

Next, add the following configuration in the application.properties file:

server.port=8765
eureka.instance.hostname: localhost
eureka.client.registerWithEureka: false
eureka.client.fetchRegistry: false
eureka.client.serviceUrl.defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

If you can start this program successfully, you can see the following pages in the address of http://localhost:8765:

Client

Create another Spring Starter Project.

Add the @ EnableDiscoveryClient tag to the entry method.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@EnableDiscoveryClient
@RestController
@SpringBootApplication
public class SpringcloudEurekaClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudEurekaClientApplication.class, args);
    }
    
    @RequestMapping("/hello")
    public String home() {
        return "Hello world";
    }
}

Add server address in configuration file

server.port=8760

spring.application.name: springcloud-eureka-client
eureka.client.serviceUrl.defaultZone: http://localhost:8765/eureka/

After starting the client, refresh the server page, and you can see that the client service has been found and registered by the server.

Posted by atstein on Fri, 27 Dec 2019 10:44:10 -0800