This article is excerpted from the author’s book Spring Cloud Advances in Microservices Architecture

What is service registration and discovery

In the traditional monomer application, the invocation between components is carried out through the interface with standard constraints, which achieves good cooperation between different modules. In micro service architecture, the original ‘stones’ application in accordance with the business is divided into relatively independent, provides the specific functions of service, every micro service through cluster or other means for dynamic extension, every micro service instance network address may dynamic change, which makes originally by hard-coded address call way lost its applicability. In the micro-service architecture, the service span is so large and the number is so large that it is urgent for the architecture to establish a decentralized component to register and manage the information of each micro-service instance, and at the same time provide the ability for each micro-service instance to discover each other, so as to achieve the result of mutual invocation.

Generally speaking, service registration and discovery consists of two parts, one is the Server side, the other is the Client. A Server is a common component that provides service registration and discovery functions for clients, maintains information about clients registered with the Server, and provides interfaces for clients to obtain information about other services in the registry. In this way, dynamically changing clients can make calls between services at time nodes with stable service addresses. The Client registers its service information with the Server in a certain way and maintains the consistency of its own information within the normal range. In this way, other services can discover the Client and obtain dependent service information from the Server to complete service invocation.

Eureka profile

The word Eureka comes from the ancient Greek word meaning “Eureka! I found it!” According to legend, Archimedes discovered the principle of buoyancy while taking a bath and was too happy to put on his trousers to run into the street Shouting, “Eureka!” .

In Netflix, Eureka is a REST-style service registry and discovery infrastructure that applies load balancing and failover to middle-tier services in AWS. Eureka consists of two parts. One is Eureka Server, which provides the functions of service registration and discovery, namely, the Server side mentioned above. The other is the Java Client, called Eureka Client, to make the interaction with the Server easier. The Eureka Client will register its information with the Eureka Server periodically and discover other services from the Server. The client has a built-in load balancer for basic cyclic load balancing.

The Spring Cloud version is based on finchley.m9, the Spring-Cloud-Netflix version is based on 2.0.0.m8, and Eureka is based on V1.8.7.

Set up Eureka service registry

You can quickly build SpringBoot projects with Eurake Server dependencies through IDEA

Mainly depends on

<dependency> // Eureka-client dependencies
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency> // Actuator dependence
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency> // Spring Web MVC dependencies
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Copy the code

The annotation @enableeurekaserver in the startup class

The @springBootApplication // @enableeurekaserver annotation will automatically configure the required configuration classes for the project, Identify the registry @ EnableEurekaServer services for the public class Chapter4EurekaServerApplication {public static void main (String [] args) { SpringApplication.run(Chapter2EurekaServerApplication.class, args); }}Copy the code

Add the following configuration to the application.yml configuration file to configure the registry’s port and identify itself as Eureka Server.


server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false  // Indicates that the service does not communicate to Eureka The Server registers its own information
    fetch-registry: false // Indicates that the service does not communicate to Eureka Server Obtains registration information
    service-url:  // Eureka Server Address of the register center, used by clients to communicate with servers
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Copy the code

Eureka Server can be deployed independently or in a cluster. In a cluster deployment, registry information is synchronized between Eureka servers. In this case, the Eureka Server whose registry information is synchronized is called the peer by the Eureka Server whose registry information is synchronized.

Note that the service-URL in the above configuration actually points to the registry itself. Generally speaking, each Eureka Server is also a Eureka Client, which tries to register itself. Therefore, at least one URL of the registry is required to locate the peer. If such a registration endpoint is not provided, the registry will work, but will print in the log that it cannot register itself with the peer. In Standalone Eureka Server mode, the Eureka Server will normally turn off registering itself as a client and the registry will not be registered with its peer.

The Eureka Server and The Eureka Client are maintained through Heartbeat. The Heartbeat means that the Eureka Client periodically reports the status of the current service instance to the Eureka Server.

Eureka Server needs to keep the service instance information up to date at all times, so each service instance in the registry needs to send a heartbeat to the Server periodically to keep its registry up to date (data is usually stored directly in memory). This means that the Eureka Client does not need to request dependent service instance information from the registry for each interservice request. The Eureka Client will periodically pull all information in the registry from the Eureka Server and cache the registry information locally. Used for service discovery.

After the Eureka Server is started, the application has a home page to display the service instance information in the current registry and expose the HTTP endpoint used by the Eureka Client in the/Eureka path to register itself, obtain registry information, and send heartbeat messages.

Set up Eureka service provider

You can quickly build SpringBoot projects with Eurake Client dependencies through IDEA.

Mainly rely on:

	
<dependency>// Eureka-server dependencies<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

Start the class

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

In Finchley’s version of Spring Cloud, once the spring-cloud-starter-Netflix-Eureka-client dependency is introduced, the application will automatically register with the Eureka Server. However, you need to add the address of the Eureka Server to the configuration file.

Add the following configuration to application.yml:

eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url: // Eureka Server Address of the register center, used by clients to communicate with servers
      defaultZone: http://localhost:8761/eureka/ 

server:
  port: 8765
spring:
  application: 
    name: eureka-client

Copy the code

View the Eureka Service Registry

After setting up the above two Eureka applications, start Server and Client in turn.

Eureka Server home page

Visit the homepage of Eureka Server http://localhost:8761, and you can see the following interface:

  1. Information about the service instance currently registered with Eureka Server
  2. General information about the Eureka Server running environment
  3. Eureka Server instance information

Exchange information with the service registry

DiscoveryClient comes from Spring-Cloud-client-Discovery, which is a top-level interface defined in SpringCloud for service discovery. There are implementations in SpringCloud’s various service discovery components, such as Netflix Eureka or Consul. It provides the ability to retrieve service instance information from the service registry based on the serviceId.

When a service instance has a concrete implementation of DiscoveryClient, other service instances can be discovered from Eureka Server.

Inject DiscoveryClient into Eureka Client and obtain service instance information from Eureka Server.

In chapter2 – eureka – client add a ServiceInstanceRestController controller

@RestController
public class ServiceInstanceRestController {
    @Autowired
    private DiscoveryClient discoveryClient;
    @RequestMapping("/service-instances/{applicationName}")
    public List<ServiceInstance> serviceInstancesByApplicationName(
            @PathVariable String applicationName) {
        returnthis.discoveryClient.getInstances(applicationName); }}Copy the code

After start the application, visit the address http://localhost:8765/service-instances/eureka-client, get application called eureka – client (service) service instance metadata, the results are as follows:

[
    {
        "host":"192.168.1.168".
        "port":8765.
        "metadata":{
            "management.port": "8765",
            "jmx.port": "59110"
        },
        "uri":"http://192.168.1.168:8765".
        "secure":false.
        "serviceId":"EUREKA-CLIENT".
        "instanceInfo":{
            "instanceId":"192.168.1.168: eureka - client: 8765".
            "app":"EUREKA-CLIENT".
            "appGroupName":null.
            "ipAddr":"192.168.1.168".
            "sid":"na".
            "homePageUrl":"http://192.168.1.168:8765/".
            "statusPageUrl":"http://192.168.1.168:8765/info".
            "healthCheckUrl":"http://192.168.1.168:8765/health".
            "secureHealthCheckUrl":null.
            "vipAddress":"eureka-client".
            "secureVipAddress":"eureka-client".
            "countryId":1.
            "dataCenterInfo":{
                "@class":"com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
                "name":"MyOwn"
            },
            "hostName":"192.168.1.168".
            "status":"UP".
            "leaseInfo":{
                "renewalIntervalInSecs":30.
                "durationInSecs":90.
                "registrationTimestamp":1515585341831.
                "lastRenewalTimestamp":1515585341831.
                "evictionTimestamp":0.
                "serviceUpTimestamp":1515585341260
            },
            "isCoordinatingDiscoveryServer":false.
            "metadata":{
                "management.port": "8765",
                "jmx.port": "59110"
            },
            "lastUpdatedTimestamp":1515585341831.
            "lastDirtyTimestamp":1515581890364.
            "actionType":"ADDED".
            "asgName":null.
            "overriddenStatus":"UNKNOWN"
        }
    }
]
Copy the code

Standard metadata in Eureka include host name, IP address, port number, status page URL, and health check URL. These metadata are stored in the registration table of Eureka Server. The Eureka Client reads these metadata according to the service name to discover and invoke other service instances. Metadata can be customized to suit specific business scenarios, as described in the following sections.

Learn more about this book:address

Recommended reading

A collection of microservices

Subscribe to the latest articles, welcome to follow my official account