Information-SpringCloud Microservice Architecture

1. Case Construction

In a distributed system using a microservice architecture, microservices communicate over a network.
We describe the invocation relationship between microservices through service providers and service consumers .

Service provider: the callee of the service, the party that provides the call interface
Service consumer: the caller of the service, the party that depends on other services

Let's take the example of a user placing an order that is common in an e-commerce system. The user initiates a purchase request to the order microservice. Before saving the order,
it is necessary to call the product microservice to query the current product inventory, unit price and other information. In this scenario, the order microservice is a service consumer
, and the product microservice is a service provider
insert image description here

2.1 Database tables

The data provides the database tables and entity class
user tables required in the case

CREATE TABLE `tb_user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(40) DEFAULT NULL COMMENT '用户名',
 `password` varchar(40) DEFAULT NULL COMMENT '密码',
 `age` int(3) DEFAULT NULL COMMENT '年龄',
 `balance` decimal(10,2) DEFAULT NULL COMMENT '余额',
 `address` varchar(80) DEFAULT NULL COMMENT '地址',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Product list

CREATE TABLE `tb_product` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `product_name` varchar(40) DEFAULT NULL COMMENT '名称',
 `status` int(2) DEFAULT NULL COMMENT '状态',
 `price` decimal(10,2) DEFAULT NULL COMMENT '单价',
 `product_desc` varchar(255) DEFAULT NULL COMMENT '描述',
 `caption` varchar(255) DEFAULT NULL COMMENT '标题',
 `inventory` int(11) DEFAULT NULL COMMENT '库存',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

order form

CREATE TABLE `tb_order` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) DEFAULT NULL COMMENT '用户id',
 `product_id` int(11) DEFAULT NULL COMMENT '商品id',
 `number` int(11) DEFAULT NULL COMMENT '数量',
 `price` decimal(10,2) DEFAULT NULL COMMENT '单价',
 `amount` decimal(10,2) DEFAULT NULL COMMENT '总额',
 `product_name` varchar(40) DEFAULT NULL COMMENT '商品名',
 `username` varchar(40) DEFAULT NULL COMMENT '用户名',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2.2 Build environment

(1) Create a parent project shop_parent
to create a parent project in IDEA shop_parentand introduce coordinates

<?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.itcast</groupId>
    <artifactId>spring_cloud_demo</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>


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

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


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

2.3 Build commodity microservices

product's pom file

<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--引入EurekaClient-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

2.3.1 Writing Entity Classes

Create cn.itcast.entity.Product entity class and configure

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;

@Data
@Entity
@Table(name="tb_product")
public class Product {
    
    
    @Id
    private Long id;
    private String productName;
    private Integer status;
    private BigDecimal price;
    private String productDesc;
    private String caption;
}

2.3.2 Write dao interface

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface ProductDao extends JpaRepository<Product,Long>, JpaSpecificationExecutor<Product> {
    
    }

2.3.3 Writing the service layer

public interface ProductService {
    
    

    /**
     * 根据id查询
     */
    Product findById(Long id);

    /**
     * 保存
     */
    void save(Product product);
    /**
     * 更新
     */
    void update(Product product);
    /**
     * 删除
     */
    void delete(Long id);
}

@Service
public class ProductServiceImpl implements ProductService {
    
    

    @Autowired
    private ProductDao productDao;

    @Override
    public Product findById(Long id) {
    
    
        return productDao.findById(id).get();
    }

    @Override
    public void save(Product product) {
    
    
        productDao.save(product);
    }

    @Override
    public void update(Product product) {
    
    
        productDao.save(product);
    }

    @Override
    public void delete(Long id) {
    
    
        productDao.deleteById(id);
    }
}

2.3.4 Writing the web layer

@RestController
@RequestMapping("/product")
public class ProductController {
    
    
    @Autowired
    private ProductService productService;

    @GetMapping("/{id}")
    public Product findById(@PathVariable Long id) {
    
    
        return productService.findById(id);
    }
    @PostMapping
    public String save(@RequestBody Product product) {
    
    
        productService.save(product);
        return "保存成功";
    }
    @PutMapping("/{id}")
    public String update(@RequestBody Product product) {
    
    
        productService.update(product);
        return "修改成功";
    }
    @DeleteMapping("/{id}")
    public String delete(Long id) {
    
    
        productService.delete(id);
        return "删除成功";
    }
}

The @GetMapping used in the controller is a combined annotation, which is equivalent to @RequestMapping(method="get").
Similar annotations include @PostMapping, @PutMapping, @DeleteMapping

2.3.5 Configure startup class

@SpringBootApplication(scanBasePackages="cn.itcast")
@EntityScan("cn.itcast.entity")
public class ProductApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(ProductApplication.class, args);
    }
}

2.3.6 Configure yml file

server:
  port: 9001 #端口
spring:
  application:
    name: service-product #服务名称
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true

2.3.7 Testing

insert image description here

2.4 Other Microservices

order 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">
    <parent>
        <artifactId>spring_cloud_demo</artifactId>
        <groupId>cn.itcast</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Order</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

</project>

2.5 Service call

The basic microservice has been written in the previous article, and the product microservice needs to be called to obtain product data when the user places an order. So what should be done
? Everyone knows that commodity microservices provide HTTP interfaces for people to call. Therefore, when placing an order, you can use related tools for http requests
, such as the common HttpClient, OkHttp, and of course you can also use the RestTemplate provided by Spring.

2.5.1 Introduction to RestTemplate

  1. The RestTemplate class provided by the Spring framework can be used to call the rest service in the application. It simplifies the communication method with the http service, unifies the
    RESTful standard, and encapsulates the http link. We only need to pass in the url and the return value type. Compared with the previously commonly used
    HttpClient, RestTemplate is a more elegant way to call RESTful services.
  2. Accessing third-party REST services in a Spring application is all about using the Spring RestTemplate class. The RestTemplate class is designed
    on the same principles as many other Spring template classes (eg JdbcTemplate, JmsTemplate), providing a simplified
    way to perform complex tasks with default behavior.
  3. By default, RestTemplate relies on the JDK's ability to provide http connections (HttpURLConnection). If necessary, it can also be
    replaced by other HTTP libraries such as Apache HttpComponents, Netty or OkHttp through the setRequestFactory method.
  4. Considering that the RestTemplate class is designed for invoking REST services, it is not surprising that its main methods are closely related to the fundamentals of REST,
    which are the methods of the HTTP protocol: HEAD, GET, POST, PUT, DELETE, and OPTIONS. For example,
    the RestTemplate class has methods such as headForHeaders(), getForObject(), postForObject(), put(), and delete().

2.5.2 RestTemplate method introduction

insert image description here

2.5.3 Call microservices through RestTemplate

(1) Configure RestTemplate in the ProductApplication startup class in the shop_service_order project


@SpringBootApplication
@EntityScan("cn.itcast.order.entity")
public class OrderApplication {
    
    

	/**
	 * 使用spring提供的RestTemplate发送http请求到商品服务
	 *      1.创建RestTemplate对象交给容器管理
	 *      2.在使用的时候,调用其方法完成操作 (getXX,postxxx)
	 * * 
	 */
	@Bean
	public RestTemplate restTemplate() {
    
    
		return new RestTemplate();
	}

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

(2) Write the method of placing an order

@RestController
@RequestMapping("/order")
public class OrderController {
    
    
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/{id}")
    public String order(Integer num) {
    
    
        //通过restTemplate调用商品微服务
        Product object =
                restTemplate.getForObject("http://127.0.0.1:9001/product/2", Product.class);
        System.out.println(object);
        return "操作成功";
    }
}

test
insert image description here

2.5.4 Problems with hard coding

So far, the RESTFul API interface of commodity microservices can be called through RestTemplate. But we have hard-coded the provider's network address
(ip, port) into the code, which has many problems:

  • Application scenarios are limited
  • cannot be adjusted dynamically

So how to solve it, you need to dynamically register and discover services through the registration center

3 Service Registration Eureka Basics

3.1 Registration Center of Microservices

The registration center can be said to be the "address book" in the microservice architecture, which records the mapping relationship between services and service addresses. In the distributed architecture,
the service will be registered here. When the service needs to call other services, find the address of the service here and call it.
insert image description here

3.1.1 The main role of the registration center

The service registry (hereinafter referred to as the registry) is a very important component of the microservice architecture, and it mainly plays the role of a coordinator in the microservice architecture
. The registration center generally includes the following functions:

  1. Service discovery:
    Service registration/anti-registration: Save information of service provider and service caller
    Service subscription/unsubscription: Service caller subscribes to service provider information, preferably with real-time push function
    Service routing (optional): Yes Ability to screen integration service providers.
  2. Service configuration:
    configuration subscription: service providers and service callers subscribe
    to microservice-related configurations Configuration delivery: proactively push configurations to service providers and service callers
  3. Service health detection
    Detect the health of service providers

3.1.2 Common Registration Centers

insert image description here

3.2 Overview of Eureka

3.2.1 Basic knowledge of Eureka

Eureka is a service discovery framework developed by Netflix. SpringCloud integrates it into its sub-project spring-cloud-netflix to
realize SpringCloud's service discovery function.
insert image description here
The above figure briefly describes the basic architecture of Eureka, which consists of 3 roles:
1. Eureka Server
provides service registration and discovery
2. Service Provider
The service provider
registers its own services to Eureka, so that service consumers can find
3. Service Consumer
The service consumer
obtains the registered service list from Eureka, so that the service can be consumed

3.2.2 Eureka's interaction process and principle

insert image description here
The picture is from the official Eureka architecture diagram, which roughly describes the working process of the Eureka cluster. There are so many components in the figure, it may be
difficult to understand, let's explain it in plain language:

  • Application Service is equivalent to the service provider in this book, and Application Client is equivalent to the service consumer;
  • Make Remote Call can be simply understood as calling RESTful API;
  • us-east-1c, us-east-1d, etc. are all zones, and they all belong to the region us-east-1;

As can be seen from the figure, Eureka includes two components: Eureka Server and Eureka Client, and their functions are as follows:

  • Eureka Client is a Java client for simplifying interaction with Eureka Server;
  • Eureka Server provides the capability of service discovery. When each microservice starts, it will report to Eureka Server through Eureka Client
  • Register your own information (such as network information), and Eureka Server will store the service information;
  • After the microservice starts, it will periodically send a heartbeat to Eureka Server (the default period is 30 seconds) to renew its own information. If
    Eureka Server does not receive the heartbeat of a microservice node within a certain period of time, Eureka Server will log off the microservice
    node (90 seconds by default);
  • Each Eureka Server is also a Eureka Client, and multiple Eureka Servers are replicated to complete
    the synchronization of the service registry;
  • Eureka Client caches information in Eureka Server. Even if all Eureka Server nodes are down, service consumers
    can still use the information in the cache to find service providers.

In summary, Eureka improves the flexibility, scalability, and availability of the system through mechanisms such as heartbeat detection, health checks, and client-side caching
.

3.3 Build Eureka Registration Center

3.3.1 Build Eureka Service Center

(1) Create eureka_server submodule
(2) Introduce maven coordinates

<?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>spring_cloud_demo</artifactId>
        <groupId>cn.itcast</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eureka_server</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

(3) Configure application.yml

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

registerWithEureka: Whether to register yourself in the Eureka service, which is all without registration
fetchRegistry: Whether to obtain registration information from Eureka
serviceUrlEureka: The address where the client interacts with the Eureka server

(4) Configure the startup class

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

EnableEurekaServer : activate Eureka Server side configuration

3.3.2 Service registry management background

Open the browser and visit http://localhost8761 to enter the built-in management console of EurekaServer, the display effect is as follows
insert image description here

3.4 Service registration to Eureka registration center

3.4.1 Registration of goods and services

(1) Introduce the coordinates in the commodity module
Add the relevant coordinates of the eureka client in the pom file of shop_service_product

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

(2) Configure the application.yml file
Add the host address of Eureka Server in the application.yml of the project

eureka:
 client:
   serviceUrl: # eureka server的路径
     defaultZone: http://localhost:8761/eureka/
 instance:
   prefer-ip-address: true #使用ip注册

(3) Modify the startup class to add service registration annotations

@SpringBootApplication
//@EnableDiscoveryClient
//@EnableEurekaClient
public class UserApplication {
    
    
 public static void main(String[] args) {
    
    
 SpringApplication.run(UserApplication.class, args);
 }
}

Starting from Spring Cloud Edgware version, @EnableDiscoveryClient or
@EnableEurekaClient can be omitted. Just add the relevant dependencies and configure accordingly to register the microservice to the service discovery component.

3.5 Self-protection in Eureka

After the microservice is successfully registered for the first time, a heartbeat will be sent every 30 seconds to register the instance information of the service to the registration center. Notify Eureka
Server that the instance still exists. If no update is sent for more than 90 seconds, the server will remove the service from the registry.

During the operation of Eureka Server, it will count whether the proportion of heartbeat failures is lower than 85% within 15 minutes. If it is lower than the situation (it is easy to
meet during stand-alone debugging, the actual production environment is usually due to network instability. result), Eureka Server will
protect the current instance registration information and prompt this warning.
The protection mode is mainly used for protection in the case of a network partition between a group of clients and Eureka Server . Once in protection mode, Eureka Server will try to protect the information in its service registry
and no longer delete the data in the service registry (that is, it will not log out any microservices)

After verifying that the self-protection mechanism is enabled, it will not be displayed on the web immediately, but will wait for 5 minutes by default (can be
configured by eureka.server.wait-time-in-ms-when-sync-empty), that is, 5 minutes Finally, you will see the following prompt message:
insert image description here
If self-protection is turned off, turn off the self-protection function by
setting .eureka.enableSelfPreservation=false

3.6 Metadata in Eureka

There are two types of metadata in Eureka: standard metadata and custom metadata.

  • Standard metadata: information such as host name, IP address, port number, status page, and health check, which will be published in the service registry
    for calls between services.
  • Custom metadata: You can use eureka.instance.metadata-map configuration, which conforms to the storage format of KEY/VALUE. These
    metadata can be accessed in remote clients.

In the program, DiscoveryClient can be used to obtain all metadata information of the specified microservice


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class T {
    
    
    @Autowired(required = false)
    private ProductDao dao;
    @Test
    public void setDao(){
    
    
        List<Product> all = dao.findAll();
    }
    @Test
    public void d(){
    
    
        dao.findAll().forEach(System.out::println);
    }

    @Autowired(required = false)
    private DiscoveryClient discoveryClient;
    @Test
    public void test(){
    
    
        System.out.println("---------------这里是分割线---------------");
        List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PRODUCT");
        for (ServiceInstance instance : instances) {
    
    
            System.out.println(instance);
        }
        System.out.println("---------------这里是分割线---------------");
    }
}

insert image description here

4 Service Registration Eureka Advanced

5 Eureka replacement program Consul

5.1 The impact of Eureka closed source

insert image description here

5.1.2 Alternatives to Eureka

Zookeeper
ZooKeeper is a distributed, open source distributed application coordination service, an open source implementation of Google's Chubby
, and an important component of Hadoop and Hbase. It is a software that provides consistent services for distributed applications. Its functions include
: configuration maintenance, domain name service, distributed synchronization, group service, etc.
Consul
consul is a popular service discovery tool in recent years. It is used in work, so let’s have a brief understanding. Three main application scenarios of consul:
service discovery, service isolation, and service configuration.
Nacos
Nacos is a new open source project launched by Alibaba. It is a dynamic service discovery, configuration management
and service management platform that makes it easier to build cloud-native applications. Nacos is dedicated to helping you discover, configure and manage microservices. Nacos provides a set of easy-to-use features
to help you quickly realize dynamic service discovery, service configuration, service metadata, and traffic management.
Nacos helps you build, deliver and manage microservice platforms more agilely and easily .
Nacos is a service infrastructure for building a "service"-centric modern application architecture (such as microservice paradigm, cloud native paradigm).

5.2 What is consul

5.3 Basic use of consul

5.4 Consul-based service registration

5.4.1 Case preparation

(1) Copy a new project for configuration Copy a new
project, name it shop_consul_parent, and import related submodules
(2) Modify the relevant pom files of microservices
Modify the pom files of each microservice and add SpringCloud Provided Consul-based dependencies

 <!--SpringCloud提供的基于Consul的服务发现-->
 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
 <!--actuator用于心跳检查-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

Among them spring-cloud-starter-consul-discoveryare related dependencies on consul support provided by SpringCloud.
spring-boot-starter-actuatorRelated dependencies for completing heartbeat detection responses.

5.4.2 Configure service registration

Modify the application.yml configuration file of each microservice, and add relevant configuration information discovered by the consul service

spring:
 ...省略
 cloud:
   consul: #consul相关配置
     host: 192.168.74.101 #ConsulServer请求地址
     port: 8500 #ConsulServer端口
     discovery:
        #是否注册
       register: true
        #实例ID
       instance-id: ${
    
    spring.application.name}-1
        #服务实例名称
       service-name: ${
    
    spring.application.name}
        #服务实例端口
       port: ${
    
    server.port}
        #健康检查路径
       healthCheckPath: /actuator/health
        #健康检查时间间隔
       healthCheckInterval: 15s
        #开启ip地址注册
       prefer-ip-address: true
        #实例的请求ip
       ip-address: ${
    
    spring.cloud.client.ip-address}

insert image description here

5.4.3 View the service list in the console

Open the management console of ConsulServer, and you can find that all three microservices have been registered in Consul.
insert image description here

5.5 service discovery based on consul

Because SpringCloud encapsulates Consul. It is consistent with Eureka for obtaining service provider information on the consumer side. Also
use DiscoveryClient to complete the call to obtain microservice instance information

6 Getting Started with Service Call Ribbon

After the above study, service registration and service discovery have been realized. When a service is started,
the information can be registered to the registration center through HTTP, and the service list of the registration center can be obtained through the tools provided by SpringCloud. However, there are still many problems in calling between services
, such as how to call microservices more conveniently, how to choose multiple microservice providers, how to load balance,
etc.

6.2 Ribbon overview

6.2.1 What is Ribbon

is a load balancer released by Netflix that helps control HTTP and TCP client behavior. In SpringCloud,
Eureka is generally used with Ribbon. Ribbon provides the function of client load balancing. Ribbon uses the
service information read from Eureka to reasonably load when invoking services provided by service nodes.
In Spring Cloud, the registration center and Ribbon can be used together. The Ribbon automatically obtains the list information of service providers from the registration center
, and requests services based on the built-in load balancing algorithm.

6.2.2 The main function of Ribbon

(1) Service invocation
The service invocation is implemented based on the Ribbon, which is composed of a (service name-request path) mapping relationship by pulling all the service lists. With the help of
RestTemplate, the final call
(2) load balancing
When there are multiple service providers, Ribbon can automatically select the service address to be called according to the load balancing algorithm


7 Service Call Ribbon Advanced

7.1 Overview of load balancing

7.1.1 What is load balancing

When building a website, if the performance and reliability of the web service of a single node cannot meet the requirements; or when using external network services, you are often worried about being
hacked, and you will accidentally open the external network port. Usually this Adding load balancing at the right time can effectively solve service problems
.


Load balancing is a basic network service. Its principle is to distribute traffic to the back-end service cluster through the load balancing service running in front of it according to the specified load balancing algorithm, so as to provide the system with the capability of parallel expansion.

The application scenarios of load balancing include traffic packets, forwarding rules, and back-end services. Since this service has functions such as internal and external network instances and health checks, it
can effectively provide system security and availability.

Guess you like

Origin blog.csdn.net/fgwynagi/article/details/130369664