In the last one First time to know SpringCloud Microservices in , We briefly talk about service providers and consumers , When there are more services , There will be confusion between dependence and management , And the need to expose their address , To solve these problems , We learn Eureka Registry Center .

  Eureka Registry Center

1. know Eureka

First of all, let's solve the first problem , Management of services .

Problem analysis

In the case just now ,user-service External services , Need to expose your address . and consumer( caller ) The address of the service provider needs to be recorded . Address change in the future , It needs to be updated in time . It doesn't feel like much when there's less service , But in today's increasingly complex Internet Environment , One project will definitely be divided into more than ten , Even dozens of microservices . At this time, if the administrator still manages the address , Not only development difficulties , Future testing 、 It will be very troublesome to launch , This is related to DevOps Our thoughts are contrary .

online car-hailing

It's like Before the appearance of online car Hailing , When people go out for a taxi, they can only call a taxi . Some private cars want to rent but are not qualified , It's called the black car . And a lot of people want a car appointment , But there are too few taxis , inconvenient . There are many private cars, but they dare not stop them , And cars all over the street , Who knows which one is willing to carry people . One wants , One is willing to give , It's just a lack of introducers , Lack of management .

At this time, Didi, such as the network car Hailing platform, appears , All private cars that want to carry passengers are registered in Didi , Record your model ( Service type ), Identity information ( Contact information ). Private cars providing services in this way , It can be found in Didi , Be clear at a glance .

People who want to call at this time , Just open it APP, Enter your destination , Choice of vehicle type ( Service type ), Didi automatically arranges a car to meet your needs , Serve you , perfect !

Eureka What do you do ?

Eureka It's like dripping , Responsible for managing the 、 Record service provider information . Service callers don't need to find their own services , It's about telling your needs Eureka, then Eureka Will tell you the services that meet your needs .

meanwhile , Service provider and Eureka Through between “ heartbeat ” Mechanism for monitoring , When a service provider has a problem ,Eureka It will naturally be removed from the list of services .

This enables automatic registration of services 、 Find out 、 Condition monitoring .

2. Schematic diagram

Basic framework :

  • Eureka: Service registry ( It can be a cluster ), Expose your address

  • Provider : Starts to Eureka Register your own information ( Address , What services do you provide? )

  • consumer : towards Eureka A subscription service ,Eureka A list of all provider addresses for the corresponding service will be sent to the consumer , And regularly updated

  • heartbeat ( The contract ): Provider passes on a regular basis http Way to Eureka Refresh your status

3. Introductory cases

3.1. To write EurekaServer

Next we create a project , Start a EurekaServer:

Still used spring Fast build tools provided :

Selective dependency :

complete Pom file :

<?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>com.leyou.demo</groupId>
<artifactId>eureka-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>eureka-demo</name>
<description>Demo project for Spring Boot</description>

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

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- SpringCloud edition , Is the latest F series -->
<spring-cloud.version>Finchley.RC1</spring-cloud.version>
</properties>

<dependencies>
<!-- Eureka Server side -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<!-- SpringCloud rely on , Make sure to put dependencyManagement in , As a management version -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</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/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>

Write the startup class :

@SpringBootApplication
@EnableEurekaServer // Declare that this application is a EurekaServer
public class EurekaDemoApplication {

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

Write the configuration :

server:
port: 10086 # port
spring:
application:
name: eureka-server # apply name , Will be in Eureka It shows that
eureka:
client:
register-with-eureka: false # Whether to register your own information to EurekaServer, The default is true
fetch-registry: false # Whether to pull information of other services , The default is true
service-url: # EurekaServer The address of , Now it's your address , If it's a cluster , Need to add others Server The address of .
defaultZone: http://127.0.0.1:${server.port}/eureka

Start the service , And access :http://127.0.0.1:10086/eureka

3.2. take user-service Sign up to Eureka

Registration service , Is to add Eureka Client dependency for , The client code will automatically register the service to the EurekaServer in .

We are user-service-demo Add Eureka Client dependency :

To add SpringCloud rely on :

Open on startup class Eureka Client function

By adding @EnableDiscoveryClient To open Eureka Client function

@SpringBootApplication
@EnableDiscoveryClient // Turn on EurekaClient function
public class UserServiceDemoApplication {
    public static void main(String[] args) {
    SpringApplication.run(UserServiceDemoApplication.class, args);
}
}

Write the configuration

Be careful :

  • Here we add spring.application.name Property to specify the application name , It will be used in the future id Use .

  • Don't have to specify register-with-eureka and fetch-registry, Because the default is true

Restart project , visit Eureka Monitoring the page see

We found that user-service The service has been registered successfully

3.3. Consumers from Eureka Access to services

Let's modify it consumer-demo, Try from EurekaServer Access to services .

The approach is similar to that of consumers , Just add to the project EurekaClient rely on , You can get the information through the service name !

1) Add dependency :

To add SpringCloud rely on :

And then there was Eureka client :

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

2) Open in startup class Eureka client

@SpringBootApplication
@EnableDiscoveryClient // Turn on Eureka client
public class UserConsumerDemoApplication {
    @Bean
    public RestTemplate restTemplate() {
    return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
  }
  public static void main(String[] args) {
  SpringApplication.run(UserConsumerDemoApplication.class, args);
  }
}

3) Modify the configuration :

4) Modify the code , use DiscoveryClient Class method , According to service name , Get service instance :

@Service
public class UserService {

@Autowired
    private RestTemplate restTemplate;

@Autowired
    private DiscoveryClient discoveryClient;// Eureka client , Service instance information can be obtained

public List<User> queryUserByIds(List<Long> ids) {
    List<User> users = new ArrayList<>();
    // String baseUrl = "http://localhost:8081/user/";
    // According to service name , Get service instance
    List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
    // Because there's only one UserService, So we're directly get(0) obtain
    ServiceInstance instance = instances.get(0);
    // obtain ip And port information
    String baseUrl = "http://"+instance.getHost() + ":" + instance.getPort()+"/user/";
    ids.forEach(id -> {
    // We test multiple queries ,
    users.add(this.restTemplate.getForObject(baseUrl + id, User.class));
    // Each interval 500 millisecond
    try {
       Thread.sleep(500);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  });
  return users;
}
}

5)Debug Tracking operation :

Generated URL:

Access to the results :

4.Eureka Detailed explanation

Let's talk about it in detail Eureka Principle and configuration of .

4.1. Infrastructure

Eureka Three core roles in architecture :

  • Service registry

    Eureka Server application of , Service registration and discovery , That's what we just built eureka-demo

  • Service providers

    Applications providing services , It can be SpringBoot application , It can also be implemented by any other technology , As long as the external supply is Rest Style service . In this case, we implemented user-service-demo

  • Serving consumers

    Consumer app gets service list from registry , So as to know the information of each service party , Know where to call the service provider . In this case, we implemented consumer-demo

4.2. Highly available Eureka Server

Eureka Server A registry of services , In the case just now , We only have one EurekaServer, in fact EurekaServer It can also be a cluster , Form highly available Eureka center .

Service synchronization

Multiple Eureka Server They also register with each other as services , When the service provider registers with Eureka Server When a node in the cluster , This node synchronizes the service information to each node in the cluster , So as to achieve Data synchronization . therefore , No matter the client accesses Eureka Server Any node in the cluster , Can get complete service list information .

Build high availability by hand EurekaServer

Let's suppose we build two EurekaServer The cluster of , Ports are :10086 and 10087

1) We changed the original EurekaServer To configure :

So called high availability registry , It's just a way of EurekaServer Register yourself as a service , So many EurekaServer We can find each other , To form a cluster . So we made the following changes :

  • Deleted register-with-eureka=false and fetch-registry=false Two configurations . Because the default is true, So you can register yourself in the registry .

  • hold service-url The value of has been changed to another EurekaServer The address of , Not myself

2) The other configuration is just the opposite :

Be careful :idea An app in cannot be started twice , We need to reconfigure an initiator :

Then start .

3) Start the test :

4) Client registration service to cluster

because EurekaServer More than one , So when you sign up for services ,service-url Parameters need to change :

4.3. Service providers

The service provider should EurekaServer Registration service , And complete service renewal and other work .

Service registration

The service provider at startup , The :eureka.client.register-with-erueka=true Is the parameter correct , In fact, the default is true. If the value is true, Will go to EurekaServer To launch a Rest request , And carry their own metadata information ,Eureka Server It's going to be stored in a double layer Map In structure . first floor Map Of Key Is the service name , The second floor Map Of key Is an instance of a service id.

Renewal of service

After the registration service is completed , The service provider maintains a heartbeat ( Timing to EurekaServer launch Rest request ), tell EurekaServer:“ I'm still alive ”. This is what we call service renewal (renew);

There are two important parameters that can modify the behavior of service renewal :

  • lease-renewal-interval-in-seconds: Renewal of service (renew) The interval of , The default is 30 second

  • lease-expiration-duration-in-seconds: Service expiration time , The default value is 90 second

in other words , By default, each 30 Seconds service will send a heartbeat to the registry , Prove you're alive . If exceeded 90 Seconds without heartbeat ,EurekaServer It would be considered that the service is down , Will be removed from the list of services , Do not modify these two values in the production environment , The default can be .

But in development , This value is a little too long , Often we turn off a service , Will find Eureka Still think service is alive . So we can reduce it properly in the development stage .

example id

Let's take a look at the service status information :

stay Eureka Monitoring the page , View service registration information :

stay status A column , Display the following information :

  • UP(1): The delegate is now activated 1 Example , No cluster

  • DESKTOP-2MVEC12:user-service:8081: Is the name of the example (instance-id),

    • The default format is :${hostname} + ${spring.application.name} + ${server.port}

    • instance-id Is the only standard to distinguish different instances of the same service , So it can't be repeated .

We can go through instance-id Property to modify its composition :

eureka:
     instance:
        instance-id: ${spring.application.name}:${server.port}

Restart the service and try again :

4.4. Serving consumers

Get a list of services

When the service consumer starts , Will detect eureka.client.fetch-registry=true The value of the parameter , If true, Will follow Eureka Server List of services read only backup , Then cache locally . also every other 30 second Data will be retrieved and updated . We can modify it with the following parameters :

eureka:
      client:
          registry-fetch-interval-seconds: 5

In production environment , We don't need to change this value .

But for the development environment , Get the latest status of services quickly , We can make it smaller .

.4.5. Failure elimination and self-protection

Failure elimination

Sometimes , Our service provider is not necessarily offline , Possible memory overflow 、 The service fails to work normally due to network failure and other reasons .Eureka Server Such services need to be excluded from the service list . So it turns on a scheduled task , every other 60 Seconds for all retired services ( exceed 90 Seconds not responding ) Culling .

Can pass eureka.server.eviction-interval-timer-in-ms Parameter to modify it , In milliseconds , Do not modify the build environment .

This will bring great inconvenience to our development , You restart the service , Separated 60 second Eureka That's how it came about . The development stage can be adjusted appropriately , such as 10S

Self protection

We shut down a service , Will be in Eureka Panel sees a warning :

It's triggered Eureka Self-protection mechanism . When a service fails to renew its heartbeat on time ,Eureka Will count the latest 15 Does the percentage of service instances with heartbeat failure exceed 85%. In production environment , Because of network delay and other reasons , The proportion of heart failure instances is likely to exceed the standard , But it's not appropriate to exclude services from the list at this time , Because the service may not be down .Eureka The registration information of the current instance will be protected , No rejection . It works in a production environment , Ensures that most services are still available .

But it has brought troubles to our development , So in the development stage, we all turn off the self-protection mode :

eureka:
       server:
           enable-self-preservation: false # Turn off self protection mode ( Open by default )
           eviction-interval-timer-in-ms: 1000 # Interval between scan for failed services ( Default is 60*1000ms)

Microservices ---Eureka Registry Center ( Service governance ) More articles about

  1. Microservices - Eureka Registry Center

    Let's solve the first problem of microservice , Management of services . The service center provides external services , Need to expose your address . and consumer( caller ) The address of the service provider needs to be recorded . Address change in the future , It needs to be updated in time . This is not true when there is less service ...

  2. SpringCloud Micro service practice : One 、Eureka Registration center server

    1. Project start class application.java Add... To the class name @EnableEurekaServer annotation , The statement is the registry 1 import org.springframework.boot.SpringAp ...

  3. Spring Cloud-- build Eureka Registry Services

    Use RestTemplate The disadvantages of remote service invocation : Eureka Registry Center : Eureka principle : build Eureka service lead pom Start class : Add... To the startup class @EnableEurekaServer annotation : To configure ...

  4. Spring Cloud Eureka Registry Center Serving consumers The relationship between service providers and the connection between high availability

    Registry Center : Provide service registration and query ( Find out ) Service providers : Service provider , The party providing the services . Serving consumers : The consumer of the service , The party using the service . We don't have a registry , Service providers and service consumers can also call , adopt spring in ...

  5. feign call spring clound eureka Registry Services

    @RestController public class TestService { private TestApi computeClient; private static final Strin ...

  6. ( turn ) Microservices _ Create a simple Eureka Registry Center

    Original address :https://www.cnblogs.com/lplshermie/p/9105329.html Microservices and distribution have become a very common technology , In order to keep up with the pace of the times , Recently started to learn Spring ...

  7. 14 Micro service e-commerce 【 Black horse Leyou Mall 】:day02-springcloud( build Eureka Registry Center )

    Notes and materials of this project Download, Please click this sentence to get . day01-springboot( Theory Chapter ) :day01-springboot( Practice chapter ) day02-springcloud( Theory one ) ...

  8. SpringCloud Introduction to micro service Xiaobai Eureka Registration center and service center building example

    One . Registry profile Code replication area : spring: application: name: spring-cloud-server server: port: 7000 eureka: instanc ...

  9. 【 Microservices 】 The second : Starting from scratch , Easy to handle SpringCloud Micro service series -- Registry Center ( One )

    Micro service system , Effectively solve the huge project . The problem of interdependence . at present SpringCloud The system has a powerful set of solutions for micro services . In this paper , This paper focuses on the service discovery registry in the micro service system . The registry in this article , use Netf ...

Random recommendation

  1. PHP Make inquiry rental table

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  2. oracle Learn notes from scratch

    Query an existing database :select name from V$database; Unlocking users scott:alter user scott account unlock; Normal user connection :conn scott Default ...

  3. Enable test automation in Testlink

    Enabling Test Automation in Testlink   Step 1: Change config settings in testlink config file Edit c ...

  4. data structure --- The order sheet (C++)

    The order sheet It is to store the data elements of the linear table in a section of memory with consecutive addresses . It's usually implemented in one-dimensional arrays Basic operation : initialization The destruction Seeking length Search by bit According to the value lookup Insert elements Delete location i The elements of Empty operation Traversal operation Sample code : // ...

  5. Spring Boot Configure priority order

    Generally in a project , There will always be a lot of environments . such as : development environment -> Test environment -> Pre release environment -> Production environment The configuration files on each environment are always different , Even every developer's environment in a development environment may have a ...

  6. About php High concurrency solution

    Involving rush buying . seckill . Luck draw . When you grab tickets and other activities , To avoid overselling , So the stock is limited , But if the number of people placing orders at the same time exceeds the stock quantity , It will lead to oversold . So how can we solve this problem , My thinking is as follows ( Pseudo code ): sql1: Inquire about ...

  7. What I learned from the phenomenon CSS

    Text overflow hide If you've looked at floating elements , You will find the fact that , When the width of the current element is full , The latter element will fall , As shown below The code is as follows <style> div,p{ margin:0; } #bo ...

  8. SpriteBuilder in CCMotionStreak Coordinate types don't match

    stay SpriteBuilder What needs to be followed ( Or being dragged out ) The node coordinate type is the parent percentage , First, I will CCMotionStreak Its position is set to percentage type , But it doesn't work . After changing the node coordinates to the normal point type ,MotionStr ...

  9. Soft work +C(10): Team project [NABCD] - Dialogue editing

    Last one : TA guide , Continuous updating ... Next : Start from the command line and gradually develop programming ability (Java) motivation (Motivation) Eating your own dog food, also called dogfo ...

  10. 【 turn 】【 data structure 】【 Yes n The elements are put on the stack in turn , How many kinds of stack sequences are there 】

    Carter LAN number Explanation of the great God :https://blog.csdn.net/akenseren/article/details/82149145      Power encroachment and deletion The original title is There is a stack with enough capacity ,n Elements in a certain order ...