springcloud [2] Eureka registry, cluster construction and load balancing

foreword

Spring Cloud is not a single framework, but a collection of a series of frameworks, which can be said to be a family bucket of microservices, with a complete set of solutions for microservices. There are also many knowledge points, and the brain can't remember them, so I write this document in the process of learning to facilitate sorting and memory.

learning video https://www.bilibili.com/video/BV18E411x7eT?p=16

Continued from the previous article springcloud [1] Create a simple instance of the parent project

1. Introduction to Spring Cloud

Spring Cloud is an ordered collection of a series of frameworks. It uses the development convenience of Spring Boot to subtly simplify the development of distributed system infrastructure, such as service discovery registration, configuration center, message bus, load balancing, circuit breaker, data monitoring, etc., all of which can be done in the development style of Spring Boot. to one-click launch and deployment. Spring Cloud does not repeat the manufacture of wheels, it just combines the mature and practical service frameworks developed by various companies, and re-encapsulates the complex configuration and implementation principles through the Spring Boot style, and finally gives the development The author has left a set of distributed system development toolkits that are easy to understand, easy to deploy and easy to maintain. (From Baidu Encyclopedia)

1 The composition of spring cloud technology

Initial version:

Technologies are constantly being updated, and many technologies in spring cloud have been eliminated before I have time to learn. T T

Technical points after Cloud upgrade:

2 Comparison of Spring Cloud and Dubbo

The same are microservices, what is the difference between Spring Cloud and Dubbo?

1,Spring Cloud

  • It is a framework set that integrates various tools and can solve various problems in microservices
  • Based on HTTP protocol call, Rest API
  • Open source, easy to use, low cost

2,Dubbo

  • Only solve the problem of remote calls
  • Based on long connection, Java serialization call
  • To solve other problems in microservices, you need to integrate other tools or self-developed solutions

2. Basic knowledge of Eureka registration center

1. Why do you need a registration center?

  • It is convenient for service providers to discover each other
    • Service providers, register their addresses with the registry
    • Service consumers, discover services from the registry
  • The address of the service provider can be changed arbitrarily, and the consumer is not affected

2. Functions of the registration center

List of addresses for maintenance services.

3. Operation parameters of eureka registry

(1) Registration

When the service provider starts, it will register with eureka'.
If the registration fails, it will try to register again and again until it succeeds.

(2) Pull

The service consumer pulls the registry from the registry.
Pull every 30 seconds to update the address table.

(3) Heartbeat

The service provider sends heartbeat data to the eureka registry every 30 seconds.

The eureka registration center, if it does not receive a heartbeat of a service for 3 consecutive times, it will consider that the service has died and the registration information will be removed.

(4) Self-protection mode

If **85%** of server heartbeats are abnormal within 15 minutes due to network instability, eureka will enter self-protection mode.

All registration information will be protected from deletion, even if three consecutive heartbeats are lost, registration information will not be deleted.

Until the network is stable, eureka will automatically exit self-protection mode.

4. eureka and zookeeper

Both are registration centers, what is the difference between the two?

  • eureka
    • AP - Availability, Partition Tolerance
    • Cluster - peer-to-peer structure
  • zookeeper
    • CP - Consistency, Partition Tolerance
    • Cluster - master-slave structure

The availability of eureka is mainly reflected in the self-preservation mode. In general, availability is more important than consistency.

5. A single eureka server

If the configuration only starts one eureka server, it will automatically configure another cluster server: localhost:8761 .

The eureka server that is started will try to connect to `localhost:8761 again and again, but if it cannot connect, it will report an error.

After setting up the eureka cluster by yourself, this error will disappear.

3. Eureka practice

1. Create Eureka service module EurekaMain7001

You can create a springboot project or a maven project.
To create a springboot project, you only need to introduce Eureka Server dependencies. If necessary, modify pom.xml and import the jar package you need.

(1) Modify pom.xml

Note: To introduce your own defined api general package, you must first introduce the jar package into the project.

<?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">
    <parent>
        <artifactId>springcloud</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-eureka-server7001</artifactId>

    <dependencies>
        <!--eureka server-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!--import your own api Generic package, you can use payment pay Entity-->
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!--boot web actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--General general configuration-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

</project>

(2) Add application.yml

server:
  port: 7001

eureka:
  instance:
    hostname: localhost #The instance name of the eureka server
  client:
    #false means not to register itself with the registry
    register-with-eureka: false
    #false means that my end is the registry, my responsibility is to maintain the service instance, and I don't need to retrieve the service
    fetch-registry: false
    service-url:
      #Both the address query service and the registration service that interact with Eureka Server need to rely on this address
      defaultZ4 one: http://${eureka.instance.hostname}:${server.port}/eureka/

(3) Add the main startup class

Added **@EnableEurekaServer** annotation to startup class

package org.example.springcloud;

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

@SpringBootApplication
@EnableEurekaServer
public class EurekaMain7001 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaMain7001.class,args);
    }
}

(4) Test after project startup

Open http://localhost:7001/
There are currently no service registrations.

2. Service registration

Register the payment service and order service written before into eureka. Since the operations are consistent, the following takes the order service (port 80) as an example.

(1) Add dependencies

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

(2) Add eureka configuration to application.yml

spring:
  application:
    name: cloud-order-server

eureka:
  client:
    #Indicates whether to register itself in EurekaServer The default is true
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka

(3) Add the annotation @EnableEurekaClient to the main startup

(4) Start the test

refresh http://localhost:7001/

You can see that the two services have been registered successfully.

3. Eureka cluster construction

(1) Create the Eureka service module cloud-eureka-server7002

The creation process is basically similar and will not be repeated here. The main thing is to modify the yml configuration file.

a) Modify the port mapping of the machine

Before modifying application.yml, you need to modify the port mapping of this machine.


After finding the file according to this path, add it at the lowest end of the file
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com

b) Modify application.yml

  • Modify 7001 application.yml
server:
  port: 7001

eureka:
  instance:
    hostname: eureka7001.com  #The instance name of the eureka server
  client:
    #false means not to register itself with the registry
    register-with-eureka: false
    #false means that my end is the registry, my responsibility is to maintain the service instance, and I don't need to retrieve the service
    fetch-registry: false
    service-url:
      #Both the address query service and the registration service that interact with Eureka Server need to rely on this address
      defaultZone: http://eureka7002.com:7002/eureka/

  • Modify 7002 application.yml
server:
  port: 7002

eureka:
  instance:
    hostname: eureka7002.com #The instance name of the eureka server
  client:
    #false means not to register itself with the registry
    register-with-eureka: false
    #false means that my end is the registry, my responsibility is to maintain the service instance, and I don't need to retrieve the service
    fetch-registry: false
    service-url:
      #Both the address query service and the registration service that interact with Eureka Server need to rely on this address
      defaultZone: http://eureka7001.com:7001/eureka/

c) Test

Open http://eureka7001.com:7001/ or http://eureka7002.com:7002/

If 7001 and 7002 can watch each other, the cluster is successfully built.

4. Register the service to the cluster

Modify the 80 and 8001 project configuration to register the service with the cluster.

	defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

Start the project, test http://eureka7001.com:7001/ and http://eureka7002.com:7002/

5. Load balancing

(1) Modify 8001 Controller

To easily view the port number of the service, add the port number information to the Controller.

package org.example.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.springcloud.entities.CommonResult;
import org.example.springcloud.entities.Payment;
import org.example.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("*******Insert result is: "+result);
        if(result>0){
            return new CommonResult(200,"successfully inserted into the database,The port number is:"+serverPort,result);
        }else{
            return new CommonResult(444,"Failed to insert into database,The port number is:"+serverPort,null);
        }
    }

    @GetMapping(value = "/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("*********The search result is: "+paymentById);
        if(paymentById!=null){
            return new CommonResult(200,"Find success,The port number is:"+serverPort,paymentById);
        }else{
            return new CommonResult(444,"find empty,find ID for: "+id +". The port number is:"+serverPort,null);
        }

    }
}

(2) Create multiple services such as: cloud-provider-payment8002

The only port number is inconsistent with the cloud-provider-payment8002 module. You can directly copy the entire project, modify the port number, and add cloud-provider-payment8002 to the parent project Pom.xml. Of course, the main startup class name should also be changed.


After creation, start the project and you can see that the project has been registered in eureka.

(3) Turn on load balancing

The interface called in the order module cannot be written dead, and the address name registered in the eureka service must be used.

a) Modify OrderController.java

  public static final String PAYMENT_URL= "http://CLOUD-PROVIDER-SERVICE";

b) Add load balancing annotation @LoadBalanced to RestTemplate

(4) Test

http://localhost/consumer/payment/get/24

By default, load balancing is implemented in a round-robin manner.

  • port 8001
  • port 8001

Posted by phpORcaffine on Mon, 16 May 2022 06:18:23 +0300