Spring Cloud: Microservices and core components of Spring Cloud

Spring Cloud: Microservices and core components of Spring Cloud

Introduction to Microservices Framework

Before entering the Spring Cloud framework, we need to learn some basic concepts. First of all, we need to know what microservices are, and then how do we make remote calls to services in microservices in our daily life.

microservice

Introduction:

The microservice architecture is a way or approach to develop a single application using a set of small services. Each service is built based on a single business capability, runs in its own process, and communicates using a lightweight mechanism, usually HTTP API, and can pass Automated deployment mechanism to deploy independently. These services can be implemented using different programming languages, as well as different data storage technologies, and keep centralized management to a minimum.

Structure diagram:

insert image description here

Note: API Gateway is a server and the only entrance to the system. The gateway provides RESTful/HTTP access services. The server registers and manages services through the service registration center.

Features:

  • Single responsibility: Each service in the microservice corresponds to a unique business capability and achieves a single responsibility.
  • Service-oriented: Service-oriented means that each service must expose the service interface API to the outside world, and does not care about the technical implementation of the service. It is independent of the platform and language, and does not limit what technology is used to implement it, as long as it provides a REST interface.
  • Autonomy: Services are independent of each other and do not interfere with each other
    • Team independence: each service can be an independent development team
    • Technology independence: because it is service-oriented, as long as the corresponding REST interface is provided, what technology to use is not the key point
    • Separation of front-end and back-end: separate development of front-end and back-end, providing a unified REST interface, and the back-end does not need to develop different interfaces for PC and mobile
    • Database separation: each service uses its own data source without interfering with each other

Summarize:

Through the characteristics of microservices, we can know that when a terminal accesses a microservice project, the microservice project matches the corresponding REST interface through the API gateway, enters the corresponding service, and then realizes the function. Each service in the microservice does its own thing independently. The microservice framework is equivalent to an aggregator that integrates various services into a project to achieve a variety of functions, and each function is relatively independent without interfering with each other. It not only conforms to the loosely coupled development standard, but also makes the project easier to expand and maintain.

Remote call method

In microservices, services are connected as a whole through remote calls

Common remote calling methods are as follows:

  • RPC: Remote Procedure Call remote procedure call, similar to RMI. Custom data format, based on native TCP communication, fast and efficient. The early Web Service and the popular Dubbo are typical of RPC.
  • HTTP: HTTP is actually a network transmission protocol, based on TCP, which specifies the format of data transmission. Now the client browser and the server basically use the HTTP protocol for communication. It can also be used to make remote service calls. The disadvantage is that the message package is bloated. Now the popular REST style can be realized through the HTTP protocol.

RPC

RPC, or Remote Procedure Call (Remote Procedure Call), is a computer communication protocol. This protocol allows a program running on one computer to call a subroutine on another computer without the programmer having to program additionally for this interaction. To put it more simply: Computer A provides a service, and computer B can call the service of computer A just like calling a local service.

The RPC remote call flow chart is as follows:

insert image description here

insert image description here

Summary:
As can be seen from the above two figures, in the RPC remote call, the client and the server serialize the data that needs to be communicated and then communicate through the network through the Socket, and then receive the result data and then return it through deserialization the result of.

HTTP

HTTP is actually a network transmission protocol, based on TCP, working at the application layer, and specifying the format of data transmission. Now the client browser and the server basically use the HTTP protocol for communication, and it can also be used for remote service calls. The disadvantage is that the message package is bloated, and the advantage is that there are no technical restrictions on the service provider and the caller, which is free and flexible, and is more in line with the concept of microservices. Now the popular REST style can be realized through the HTTP protocol.

insert image description here

Remark:

  • Because RPC is defined according to the API of the language, not according to the application based on the network. So when our entire microservice architecture uses the same technology stack (for example: Java) for implementation, Dubbo can become a good microservice architecture.
  • If the technology stack used is not uniform, then Spring Cloud can be a better choice for building a microservice architecture. At this time, HTTP is used to implement calls between services.

Introduction to Spring Cloud

Introduction:

Spring Cloud is one of the projects under Spring, which mainly provides the functions of microservices.

What Spring is best at is integration. It takes the best framework in the world and integrates it into its own projects.

The same is true for Spring Cloud, which integrates some very popular technologies and implements functions such as: configuration management, service discovery, intelligent routing, load balancing, fuses, control bus, cluster status, etc.

The main components involved include:

Netflflix

  • Eureka: Registry
  • Zuul: Service Gateway
  • Ribbon: load balancing
  • Feign: service call (dynamic proxy)
  • Hystrix: Fuse

Spring Cloud

  • Gateway: service gateway, self-developed by the spring family, integrated in the framework
  • Config: distributed configuration center

The architecture diagram is as follows:

insert image description here

Version:

Spring Cloud has multiple versions, and each version corresponds to a different SpringBoot version, so when we use Spring Cloud in a project, we need to pay attention to the corresponding springboot version in the pom.xml file, so as to avoid unnecessary errors due to version mismatch mistake.

The version name of Spring Cloud mainly corresponds to the name of the London subway station in England:

insert image description here

Correspondence between Spring Cloud and Spring Boot versions:

Release Train Boot Version
Hoxton 2.2.x
Greenwich 2.1.x
Finchley 2.0.x
Edgware 1.5.x
Dalston 1.5.x

Spring Cloud Core Components

There are five core components of Spring Cloud, namely registration center, load balancing, circuit breaker, service gateway and distributed configuration center. Among them, the service gateway is mainly introduced by the Gateway in the Spring Cloud framework as an example.

Registry - Netflix Eureka

Load Balancing - Netflix Ribbon

Circuit Breaker - Netflix Hystrix

Service Gateway - Spring Cloud Gateway (Netflix Zuul)

Distributed configuration center - Spring Cloud Config

In addition, two more important components are added:

Dynamic Proxy - Feign
Service Bus - Spring Cloud Bus

Registry Eureka

Introduction:

​ When each service starts, Eureka Client will register the service to Eureka Server, and Eureka Client can also pull the registry from Eureka Server in turn, so as to know where other services are. Eureka Client includes service providers and service callers, and Eureka is responsible for managing and recording service provider information. Service callers do not need to find services by themselves, but tell Eureka their needs, and then Eureka will tell you the services that meet your needs.

At the same time, the service provider and Eureka are monitored through the "heartbeat" mechanism. When a service provider has a problem, Eureka will naturally remove it from the service list.

This enables automatic registration, discovery, and status monitoring of services.

Schematic:

insert image description here

  • Eureka: It is the service registry (it can be a cluster), which exposes its address to the outside world
  • Provider: Register your own information with Eureka after startup (address, what services to provide)
  • Consumers: Subscribe to Eureka, and Eureka will send a list of all provider addresses of the corresponding services to consumers and update them regularly
  • Heartbeat (renewal): The provider periodically refreshes its status to Eureka via HTTP

Infrastructure:

Three core roles in the Eureka architecture:

  • Service Registry

    Eureka's server application, which provides service registration and discovery functions, is the eureka-server we just established

  • service provider

    The application that provides the service can be a Spring Boot application, or it can be implemented by any other technology, as long as it provides REST-style services to the outside world.

  • service consumer

    The consumer application obtains the service list from the registration center, so as to know the information of each service provider and know where to call the service provider.

High availability Eureka Server:

Introduction:

  • Eureka can be a single one or a cluster. When our Eureka is a cluster, we call it a highly available Eureka center.
  • The so-called high-availability registration center actually registers EurekaServer itself as a service, so that multiple EurekaServers can discover each other and form a cluster.
  • Eureka Server is a web application that can start multiple instances (configure different ports) to ensure high availability of Eureka Server

Service synchronization:

​ Multiple Eureka Servers will also register with each other as services. When a service provider registers with a node in the Eureka Server cluster, the node will synchronize the service information to each node in the cluster to achieve data synchronization . Therefore, no matter whether the client accesses any node in the Eureka Server cluster, it can obtain the complete service list information.

​ As a client, you need to register information into each Eureka

​ If there are three Eurekas, each EurekaServer needs to be registered with several other Eureka services.

For example: there are three respectively 10086, 10087, 10088, then:

​ 10086 should be registered to 10087 and 10088

​ 10087 should be registered to 10086 and 10088

​ 10088 should be registered to 10086 and 10087

High availability Eureka abstract map:
insert image description here

Actual application renderings:

insert image description here

Eureka client and server configuration:

  • Eureka client project
    • user-service service provider
    • The service address uses the ip method
  • to renew
    • consumer-demo service consumption
    • How often to get the address of the service
  • Eureka server project eureka-server
    • failure rejection
    • self protection

The service provider needs to register the service with EurekaServer and complete the service renewal and other work.

service registration

When the service provider starts, it will detect whether the parameter in the configuration property: eureka.client.register-with-erueka=true is true, in fact, it is true by default. If the value is indeed true, it will initiate a Rest request to EurekaServer with its own metadata information, and EurekaServer will save this information in a two-layer Map structure.

  • The Key of the first layer of Map is the service id, which is generally the spring.application.name attribute in the configuration, user-service
  • The key of the second layer Map is the instance id of the service. General host+ serviceId + port, for example: localhost:user-service:8081
  • The value is the instance object of the service, that is to say a service, so that multiple different instances can be started at the same time to form a cluster.

By default, the host name or localhost is used for registration. If you want to register with ip, you can add the configuration in user-service as follows:

eureka: 
  instance: 
    ip-address: 127.0.0.1 # ip地址 
    prefer-ip-address: true # 更倾向于使用ip,而不是host名

Service Renewal:

After the registration service is completed, the service provider will maintain a heartbeat (regularly initiate a Rest request to EurekaServer), telling EurekaServer: "I am still alive". This we call the renewal of the service (renew);

There are two important parameters to modify the behavior of service renewal; you can add the following configuration items in user-service:

eureka: 
  instance: 
    # 服务续约(renew)的间隔,默认为30秒 
    lease-expiration-duration-in-seconds: 90
    # 服务失效时间,默认值90秒 
    lease-renewal-interval-in-seconds: 30 

That is to say, by default, the service will send a heartbeat to the registry every 30 seconds to prove that it is still alive. If no heartbeat is sent for more than 90 seconds, EurekaServer will think that the service is down and will be removed from the service list. These two values ​​should not be modified in the production environment, and the default is fine.

Get service list

When the service consumer starts, it will detect the value of the eureka.client.fetch-registry=true parameter. If it is true, it will pull the read-only backup from the list of Eureka Server services, and then cache it locally. And the data will be re-pulled and updated every 30 seconds. It can be modified by the following parameters in the consumer-demo project:

eureka: 
  client: 
    # 重新拉取服务的时间
    registry-fetch-interval-seconds: 30

Fail Rejection and Self-Protection

The following configurations are performed on the Eureka Server server side:

Service offline

When the service performs a normal shutdown operation, it will trigger a REST request for the service to go offline to the Eureka Server, telling the service registration center: "I am going offline". After receiving the request, the service center puts the service offline

failure rejection

Sometimes our service may not work properly due to memory overflow or network failure, but the service registration center has not received the "service offline" request. Compared with the "service renewal" operation of the service provider, the service registry will create a timed task at startup, and by default, the timeout in the current list (90 seconds by default) will not be renewed by default. This operation is called invalidation culling. It can be modified by the eureka.server.eviction-interval-timer-in-ms parameter in milliseconds.

self protection

When we shut down a service, we will see a red letter warning on the Eureka panel, which triggers Eureka's self-protection mechanism. When a service fails to renew the heartbeat on time, Eureka will count whether the proportion of service instances with heartbeat failures in the last 15 minutes exceeds 85%. When the EurekaServer node loses too many clients in a short period of time (a network partition failure may occur) . In a production environment, due to network delays and other reasons, the proportion of heartbeat failure instances is likely to exceed the standard, but it is not appropriate to remove the service from the list at this time, because the service may not be down. Eureka will protect the registration information of the current instance and will not remove it. This works well in a production environment, ensuring that most services are still available.

During development, in order to facilitate self-testing, self-protection is generally turned off.

Load Balancing Ribbon

Introduction:

  • When a request is initiated between services, load balancing is performed based on the Ribbon, and a suitable machine is selected from multiple machines of a service to execute the service. This is load balancing.
  • Ribbon mainly provides client-side software equalization algorithms.
  • The Ribbon client component provides a series of comprehensive configuration options, such as connection timeout, retry, retry algorithm, etc. Ribbon has built-in pluggable and customizable load balancing components.

Schematic:
insert image description here

Load balancing strategy:

  • Simple Round Robin Load Balancing
  • Weighted Response Time Load Balancing
  • Zone-aware round-robin load balancing (round-robin strategy is used by default)
  • random load balancing

Method to realize:

Because Ribbon is already integrated in Eureka, we don't need to introduce new dependencies. Add the @LoadBalanced annotation directly to the configuration method of the RestTemplate:

@Bean 
@LoadBalanced 
public RestTemplate restTemplate() { 
	return new RestTemplate(); 
}

How to modify the load balancing policy:

# 默认为轮询负载均衡,修改为随机负载均衡
user-service: 
  ribbon: 
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Breaker Hystrix

Introduction:

Hystix is ​​a delay and fault tolerance library open sourced by Netflix, which is used to isolate access to remote services and prevent cascading failures.

The request is initiated through the thread pool of Hystrix. Different services use different thread pools, which realizes the isolation of different service calls and avoids the problem of service avalanche.

principle:

Basically, the relationship between service calls is as follows: (In microservices, a business request calls four services A, H, I and P)

When all microservices are running normally, the request ends normally after the response is received, and the thread is released.

insert image description here

At this point, there is a problem with microservice I, which causes the request to not be responded to.

insert image description here

An exception occurs in microservice I, the request is blocked, and the user request will not be responded, so the thread of tomcat will not be released, so more and more user requests arrive, and more and more threads will be blocked:

insert image description here

The number of threads and concurrency supported by the server is limited, and requests are blocked all the time, which will lead to the exhaustion of server resources, resulting in the unavailability of all other services, forming an avalanche effect.

solution:

The means for Hystrix to solve the avalanche problem mainly include:

  • thread isolation
  • service downgrade

thread isolation

Schematic:

insert image description here

analyze:

  • Hystrix allocates a small thread pool for each dependent service call. If the thread pool is full, the call will be rejected immediately. By default, queuing is not used to speed up the failure judgment time.
  • The user's request will no longer directly access the service, but will access the service through the idle thread in the thread pool. If the thread pool is full or the request times out, the service will be degraded.

service downgrade

Advantages:
core services can be guaranteed first

When the user's request fails, it will not be blocked, and it will not wait endlessly or see the system crash, at least you can see an execution result (such as returning a friendly prompt message). Although the service degradation will cause the request to fail, it will not cause blocking, and at most will affect the resources in the thread pool corresponding to the dependent service, and will not respond to other services. Circumstances that trigger Hystrix service downgrade:

  • thread pool is full
  • Request timed out

The default time of request timeout is 1S, we can use the following code to modify it in the configuration file

# 默认超时时长为1S,修改为2S
hystrix:
  command:
    default: 
      execution: 
        isolation:
          thread:
            timeoutInMilliseconds: 2000

Service circuit breaker

principle:

​ In service fusing, the fuse used is also called a circuit breaker. Its English word is: Circuit Breaker. After application service fusing in a distributed system; the service caller can judge which services are slow to respond or have a large number of timeouts, and can actively fuse these services to prevent the entire system from being dragged down.

​ Hystrix's service fusing mechanism can achieve elastic fault tolerance; when the service request situation improves, it can automatically reconnect. By means of circuit breaking, follow-up requests are directly rejected, and some requests are allowed to pass after a period of time (default 5 seconds). If the call is successful, the circuit breaker will return to the closed state, otherwise it will continue to open and reject the requested service.

Schematic:

insert image description here

The 3 states of the state machine:

  • Closed : Closed state (circuit breaker closed), all requests can be accessed normally.
  • Open : In the open state (the circuit breaker is open), all requests will be downgraded. Hystrix will count the request status. When the percentage of failed requests reaches the threshold within a certain period of time, a fuse will be triggered and the circuit breaker will be fully opened. The default failure ratio threshold is 50%, and the number of requests should be at least 20.
  • Half Open : half open state, not permanent, it will enter the sleep time after the circuit breaker is opened (the default is 5S). The circuit breaker will then automatically enter the half-open state. At this time, some requests will be released to pass. If these requests are healthy, the circuit breaker will be closed, otherwise it will remain open, and the sleep timer will be performed again.

Set the fuse parameters, which can be modified in the configuration file:

hystrix: 
  command: 
    default:
      circuitBreaker: 
        errorThresholdPercentage: 50 		# 触发熔断错误比例阈值,默认值50% 
        sleepWindowInMilliseconds: 10000 	# 熔断后休眠时长,默认值5秒 
        requestVolumeThreshold: 10			# 熔断触发最小请求次数,默认值是20

Dynamic Proxy Feign

Introduction:

  • Feign is a declarative Web Service client, which makes calls between microservices easier, similar to how a controller calls a service

  • Based on Feign's dynamic proxy mechanism, according to the annotation and the selected machine, splice the request URL address, initiate the request, and realize the dynamic proxy function of the URL address.

  • Feign has automatically integrated Ribbon load balancing and Hystrix, so when we configure Feign dynamic proxy, we can directly modify the configuration file to achieve

By introducing Feign's dependencies, we can use Ribbon and Hystrix

<dependency> 
	<groupId>org.springframework.cloud</groupId> 
	<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

Implementation principle:

Create a client client by annotating @FeignClient (value="user-service"), then call the client client in the controller class, use a custom request address in the controller class, when we call the controller class to implement user When the -serivce function is used, the dynamic proxy function is used.

That is, the desired service can be accessed without using the real access address, and the function of dynamically accessing the service is realized by using the proxy address.

Load balancing in Feign

Feign integrates the function of Ribbon load balancing by default, and we can realize the function of load balancing through the configuration file

# 当我们要针对某个服务进行负载均衡的时候,仅需要在ribbon的上级目录中添加相应的服务名即可
ribbon:
  ConnectTimeout: 1000 # 连接超时时长 
  ReadTimeout: 2000 # 数据通信超时时长 
  MaxAutoRetries: 0 # 当前服务器的重试次数
  MaxAutoRetriesNextServer: 0 # 重试多少次服务
  OkToRetryOnAllOperations: false # 是否对所有的请求方式都重试

Fuse Hystrix in Feign

Feign also inherits the fuse Hystrix. When we need to use the fuse, we only need to enable the fuse service in the configuration file.

feign: 
  hystrix:
    enabled: true # 开启Feign的熔断功能

request compression

Spring Cloud Feign supports GZIP compression for requests and responses to reduce performance loss during communication. The compression function of requests and responses can be enabled by the following parameters:

feign: 
  compression: 
    request: 
      enabled: true 	# 开启请求压缩 
      mime-types: text/html,application/xml,application/json 	# 设置压缩的数据类型 
      min-request-size: 2048 	# 设置触发压缩的大小下限
    response:
      enabled: true 	# 开启响应压缩

Service Gateway Gateway

Introduction:

  • Spring Cloud Gateway provides basic gateway functions based on the Filter chain: security, monitoring/burying points, current limiting, etc.
  • Spring Cloud Gateway provides a simple, effective and unified API routing management method for microservice architecture.
  • Spring Cloud Gateway is a set of solutions to replace Netflix Zuul.
  • The core of the Spring Cloud Gateway component is a series of filters, through which the requests sent by the client can be forwarded (routed) to the corresponding microservices. Spring Cloud Gateway is a firewall and proxy added at the forefront of the entire microservice, which hides the IP port information of the microservice node, thereby enhancing security protection. Spring Cloud Gateway itself is also a microservice that needs to be registered with the Eureka service registry.

A brief understanding of the role of Gateway is: if the front-end wants to call the back-end system, then all front-end requests come in from the Gateway gateway, and the Gateway gateway forwards the request to the corresponding service after filtering.

The core functions of the gateway are: filtering and routing

Schematic:

insert image description here

Core idea:

  • Routing ( route ) The composition of routing information: it consists of an ID, a destination URL, a set of assertion factories, and a set of Filters. If the route assertion is true, the request URL matches the configured route.
  • Assertion ( Predicate ) The input type of the assertion function in Spring Cloud Gateway is ServerWebExchange in the Spring 5.0 framework. The assertion function of Spring Cloud Gateway allows developers to define matching any information from HTTP Request such as request headers and parameters.
  • Filter ( Filter ) A standard Spring WebFilter. The Filter in Spring Cloud Gateway is divided into two types of Filter, namely Gateway Filter and Global Filter. Filter Filter will modify the request and response

Use a piece of code directly to show the function of the gateway:

spring:
  application: 
    name: api-gateway 
  cloud: 
    gateway: 
      routes: 
        # 路由id,可以随意写 
        - id: user-service-route 
        # 代理的服务地址(lb表示负载均衡)
        uri: lb://user-service 
        # 路由断言,可以配置映射路径 
        predicates: 
          - Path=/api/user/** 
        filters: 
        # 添加请求路径的前缀 
        - PrefixPath=/user
        # 表示过滤1个路径,2表示两个路径,以此类推 
          - StripPrefix=1
          # 自定义过滤器 
          - MyParam=name 
        # 默认过滤器,对所有路由都生效 
        default-filters: 
          - AddResponseHeader=X-Response-Foo, Bar 
          - AddResponseHeader=myname
        # 跨域配置
        globalcors: 
          corsConfigurations: 
            '[/**]': 
            #allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
            allowedOrigins: - "http://docs.spring.io" 
            allowedMethods: - GET

analyze:

  • The route id can be written freely
  • In the service address of the proxy , lb stands for LoadBanlance, and the service name is used for load balancing configuration
  • Routing assertion : Take the example in the code, that is, the path contains the request starting with /api/user/**, proxy to the corresponding port of the service name user-service, and execute the user-service/api/user/** request service
  • Filter (add and delete prefix path): PrefixPath=/user, which means to add a user path prefix to the front end of the request address, that is, when the request address is user-service/1, the actual accessed address is user-service/user/ 1; StripPrefix=1, which means that when we use the request starting with /api/user/**, filter out the first path in the request path. For example, in this example, directly remove the api path and execute user-service/user /** service
  • Custom filter and global filter : the case in the example is mainly to add corresponding identification information to the request header data
  • Cross-domain configuration : allowedOrigins indicates the request address that is allowed to access; allowedMethods indicates the request method that allows access. As in the above code, the gateway only allows requests whose address is http://docs.spring.io and whose request method is GET to pass through

The common application scenarios of Gateway gateway filter are as follows:

  • Request authentication: Generally, before the GatewayFilterChain executes the filter method, if it finds that there is no access right, it will directly return empty.
  • Exception handling: Generally, after the GatewayFilterChain executes the filter method, it records the exception and returns it.
  • Service call duration statistics: GatewayFilterChain performs statistics based on time before and after executing the filter method.

Distributed configuration center Config

Introduction:
A distributed configuration component that places configuration files in the local or remote warehouse of the configuration service for centralized management. For example, configuration files such as application.yml can be placed on a remote Git warehouse for management.
Schematic diagram:
insert image description here
config Main configuration information:

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        #  此处使用的远程仓库为git
        git:
          uri:  				# 仓库地址,根据项目的地址来导入对应的项目
          # 因为仓库为私有,所以此处需要配置用户名和密码
          username:      # 仓库用户名
          password:       # 仓库密码

The distributed configuration center is also a microservice, so it needs to be registered in the registration center.
After setting up the configuration center, other microservice configuration files that need to place the configuration files in the remote warehouse also need to be modified:
Steps:

  1. Transfer the application.yml configuration file to the remote warehouse, and the naming format is application-profile.yml
  2. Delete the local application.yml configuration file
  3. Create a new configuration file called bootstrap.yml

bootstrap.yml configuration:

# 采用bootstrap.yml配置文件,从git仓库的配置中心中获取对应配置文件,而不在本地进行配置
# bootstrap.yml相较application.yml:bootstrap.yml更常用于系统配置,即基本不进行修改,application.yml更常用于动态调整的配置
spring:
  cloud:
    config:
      # 与git仓库中配置文件的application名一致
      name: user
      # 与git仓库中配置文件的profile名一致
      profile: dev
      # 与git仓库中配置文件存放的分支一致
      label: master
      discovery:
        # 使用配置中心
        enabled: true
        # 配置中心服务名,项目中连接配置中心模块的名称
        service-id: config-server
# 同样需要在注册中心进行注册
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

Through the above configuration, we have completed the configuration of the spring cloud config configuration center. This configuration method allows us to statically obtain the desired configuration parameters from the remote warehouse, and when the configuration file changes each time, we need The changed data can only be retrieved by restarting the local service, so it is still a little inconvenient.
In order to realize the dynamic acquisition of configuration files in the remote warehouse, we need to introduce the service bus Bus and

Service Bus Spring Cloud Bus

Introduction:

  • Spring Cloud Bus uses a lightweight message broker to connect distributed nodes, which can be used to broadcast configuration file changes or service monitoring and management. That is to say, the message bus can monitor microservices and communicate with each other between applications. Optional message brokers for Spring Cloud Bus include RabbitMQ and Kafka.
  • The bottom layer of Spring Cloud Bus is implemented based on RabbitMQ, and the local message queue service is used by default. Therefore, when using it, you need to enable the RabbitMQ service in advance to realize dynamic update of information in the form of message queues.

After introducing the Spring Cloud Bus bus function, the schematic diagram of the service call is as follows:
insert image description here
Usage:

  • config configuration center: introduce Spring Cloud Bus and RabbitMQ dependencies; modify the configuration file, add RabbitMQ parameters to realize the message queue function, and expose the address that triggers the message bus.
  • Microservice (user-service): import Spring Cloud Bus, RabbitMQ and Spring Boot Actuator dependencies; modify the bootstrap.yml configuration file, add RabbitMQ parameters to implement the message queue function
    import code:
# config配置文件

spring:
  # 配置rabbitmq信息;如果是都与默认值一致则不需要配置,rabbitmq访问地址为127.0.0.1:15672,此处使用的port只有后四位5672即可
  # 以下配置即为默认配置,可删
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
management:
  endpoints:
    web:
      exposure:
        # 暴露触发消息总线的地址
        include: bus-refresh
# user-service配置文件

spring:
  # 配置rabbitmq信息;如果是都与默认值一致则不需要配置,rabbitmq访问地址为127.0.0.1:15672,此处使用的port只有后四位5672即可
  # 以下配置即为默认配置,可删
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

After the above configuration, the Spring Cloud Bus bus service was successfully introduced, and the dynamic acquisition of configuration files in the remote warehouse was realized by using the message queue function.

Spring Cloud complete architecture diagram

insert image description here

Guess you like

Origin blog.csdn.net/xiri_/article/details/113185899