Introduction to the

In microservices, service registration and discovery play a key role in managing each microservice subsystem. As the system scale more and more, the system into a corresponding increase in the number of micro service, management and access to these services URL will become very difficult, if we each new add a small service, will be in other places use the micro service manual plus its URL address or other communication protocol, it will often make a mistake, And it’s a lot of work to manually modify the configuration files of all microservices that reference it once the address of a microservice changes. Therefore, Spring-Cloud Eureka Server is designed to solve such problems. After simple configuration, it can automatically register and discover microservices.

Based on the environment

  • JDK 1.8
  • Maven 3.3.9
  • IntelliJ 2018.1
  • Git

Program source code

Gitee yards cloud

Set up Eureka Server

Last blog we introduced how to build the configuration center of Spring-Cloud, and a test Web client to access it. This time we built a Eureka Server on the basis of the previous, and read the configuration of the configuration center. The Web client is then registered with the Eureka service as a Discovery client. First, create a new Maven project under IntelliJ:

  • groupId: cn.zxuqian
  • artifactId: registry

Then add the following code to pom.xml:

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.zxuqian</groupId>
    <artifactId>registry</artifactId>
    <version>1.0 the SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1. RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.M9</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>
Copy the code

Here, the eureka-Server core dependency spring-cloud-starter-Netflix-Eureka-server is used, as well as the client component spring-cloud-starter-config that accesses the configuration center service. Then create the bootstrap.yml file under SRC /main/resources and add the following configuration:

spring:
  application:
    name: eureka-server
  cloud:
    config:
      uri: http://localhost:8888
Copy the code

This file configures the name of the application to read the configuration file, spring.application.name, which corresponds to the file name of the service center. In addition, automatic registration and discovery of Eureka is based on this parameter. Then the URI of the configuration service center is configured. Create a new Java class, cn.zxuqian.Application, using the following code:

package cn.zxuqian;

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

@EnableEurekaServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

A single comment @enableEurekaserver is used to configure the application as EurekaServer. Then create the eureka-server.yml file in the git repository in the configuration center and add the following configuration:

server:
  port: 8761

eureka: 
 client: 
  register-with-eureka: false
  fetch-registry: false
Copy the code

This file configates the port of eureka-Server and turns off Eureka self-registration and discovery, because if not, Eureka will try to register itself during startup and an error will be reported if the service is not started. At this point, eureka Server is configured.

Update the Web Client

Now we will update the Web Client so that it can be automatically registered and discovered by Eureka. Add eureka client dependencies to pom.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Copy the code

Add the @enableDiscoveryClient annotation to the Application class:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {

    public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

Finally, we create a class to test whether the service has been successfully registered and discovered. Create a new Java class cn. Zxuqian. Controllers. ServiceInstanceController, add the following code:

package cn.zxuqian.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ServiceInstanceController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/service-instances/{applicationName}")
    public List<ServiceInstance> serviceInstancesByApplicationName( @PathVariable String applicationName) {
        return this.discoveryClient.getInstances(applicationName); }}Copy the code

This is a normal RestController that defines a variable of type DiscoveryClient and adds an @Autowire annotation. This annotation is a dependency injection feature provided by the Spring framework. In the Spring context, it automatically looks for the implementation class of DiscoveryClient, in this case Eureka Client. Some of Spring’s features and principles will be covered in a future blog post. Such also defines serviceInstancesByApplicationName method to process/service – instances / {applicationName} requests. Here {applicationName} matches the portion of the URL path after /service-instances/, and the @pathVariable annotation is assigned to the applicationName parameter of the method. Visit http://localhost:8080/service-instances/web-client, for example, then applicationName value is a web client. The discoveryClient () method returns a list of instances based on the value of Spring.application. name, which is automatically converted to a JSON array and returned to the browser.

test

Since both Eureka server and Web Client need to read the configuration from the configuration service, start config-server first, then Eureka-server, and finally web-client. After successful startup, it may take more than 10 seconds for Eureka-server to discover and register web-client. After visiting http://localhost:8080/service-instances/web-client, can get the following results:

[{"host":"xuqians-imac"."port":8080."instanceInfo": {"instanceId":"xuqians-imac:web-client"."app":"WEB-CLIENT"."appGroupName":null."ipAddr":"192.168.72.31"."sid":"na"."homePageUrl":"http://xuqians-imac:8080/"."statusPageUrl":"http://xuqians-imac:8080/actuator/info"."healthCheckUrl":"http://xuqians-imac:8080/actuator/health"."secureHealthCheckUrl":null."vipAddress":"web-client"."secureVipAddress":"web-client"."countryId":1."dataCenterInfo": {"@class":"com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"."name":"MyOwn"},"hostName":"xuqians-imac"."status":"UP"."leaseInfo": {"renewalIntervalInSecs":30."durationInSecs":90."registrationTimestamp":1525319124967."lastRenewalTimestamp":1525319124967."evictionTimestamp":0."serviceUpTimestamp":1525319124363},"isCoordinatingDiscoveryServer":false."metadata": {"management.port":"8080"},"lastUpdatedTimestamp":1525319124967."lastDirtyTimestamp":1525319124297."actionType":"ADDED"."asgName":null."overriddenStatus":"UNKNOWN"},"metadata": {"management.port":"8080"},"uri":"http://xuqians-imac:8080"."serviceId":"WEB-CLIENT"."secure":false."scheme":null}]
Copy the code

Note that the configuration center service is not set up to be registered and discovered by Eureka Server, because the configuration files are put into config-server. It has a chicken-and-egg problem with Eureka Server. Therefore, to enable config-server to be automatically registered and discovered, you need to configure Eureka server separately, and then configure the URI of Eureka in the config server. And to set the spring. Cloud. Config. Discovery. Enabled to true. Specific later need to use when detailed explanation.

conclusion

Configuring EurekaServer is fairly simple, just add an @enableEurekaserver annotation and turn off self-registration and discovery in the configuration. Then add the @enableDiscoveryClient annotation to the Application class of the client Application.

Welcome to my blog