Introduction to Spring Cloud -- Bus message Bus [essay]

Getting started with Spring Cloud -- Bus message Bus

introduce

Spring Cloud Bus is a framework used to link the nodes of distributed system with lightweight message system. It integrates the event processing mechanism of Java and the function of message middleware. Spring Cloud Bus currently supports RabbitMQ and Kafka.

Spring Cloud Bus can be used with Spring Cloud Config to dynamically refresh the configuration.

Spring Cloud Bus can manage and propagate messages between distributed systems, just like a distributed actuator. It can be used to broadcast state changes, push events, etc. it can also be used as a communication channel between microservices.

What is a bus

In the microservice architecture system, a lightweight message broker is usually used to build a common message topic and connect all microservice instances in the system. Since the messages generated in this topic will be monitored and consumed by all instances, it is called message bus. Each instance on the bus can easily broadcast some messages that need to be known by other instances connected to the subject.

Basic principles

Config Client instances listen to the same Topic in MQ (springCloudBus by default). When a service refreshes the data, it will put this information into the Topic, so that other services listening to the same Topic can be notified, and then update their own configuration.

RabbitMQ environment preparation of Bus
Linux version

Spring Cloud Bus currently supports RabbitMQ and Kafka. Here we choose to use RabbitMQ. For RabbitMQ installation and configuration, please refer to: https://blog.csdn.net/qq_39668819/article/details/107391505

As shown in the figure, we use docker to install rabbitMQ and start it successfully. After successful startup, enter the browser and open the background management interface[ http://192.168.0.163:15672/ ], as shown in the following figure: the default user name and password are guest

windows version

CSDN: uploaded installation package address: https://download.csdn.net/download/qq_39668819/13111699

1, Install Erlang, download address: http://erlang.org/download/otp_win64_22.2.exe

2, Install RabbitMQ, download address: https://dl.bintray.com/rabbitmq/all/rabbitmq-server/3.8.2/rabbitmq-server-3.8.2.exe

3, After installation, enter the sbin directory under the RabbitMQ installation directory:

In the address bar of sbin directory under RabbitMQ installation directory, enter cmd and press enter to start the command line, and then enter the following command to start the management function:

rabbitmq-plugins enable rabbitmq_management

At this time, you can search the startup and shutdown running programs of RabbitMQ

4, Visit the address to see if the installation is successful: http://localhost:15672/

Dynamic refresh global broadcast preparation
Create config client cluster

In order to demonstrate the broadcast effect, we also need to add a config client module; Similar to the configuration center cluster created earlier, we can copy 3355 to create a 3356 client module. The specific steps are as follows:

1, Set bootstrap The YML configuration file is renamed bootstrap one YML and copy it to create bootstrap - two yml´╝îbootstrap-two.yml configuration is basically the same as bootstrap one YML is consistent, mainly modifying the port number; The specific amendments are as follows:

server:
  port: 3356

eureka:
  client:
    instance-id: config-client-3356

2, Modify ConfigClientController

@RestController
@RefreshScope
public class ConfigClientController {

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

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/configInfo")
    public String getConfigInfo(){
        return "serverPort: "+port + "\t\n\n configInfo: " +configInfo;
    }
}

3, Modify the ConfigClientApplication startup service and copy a copy as ConfigClientApplication 3356. The specific modifications are as follows:

4, Start these two services, log in to Eureka registration center and check whether the service is registered successfully.

At this point, the config client cluster is created.

Dynamic refresh global broadcast design idea

There are two design ideas for dynamically refreshing the global broadcast. We will introduce these two ideas respectively below.

1, Use the message bus to trigger a client / bus/refresh, and then refresh all client configurations. [not recommended]

2, Use the message bus to trigger the / bus/refresh endpoint of a server ConfigServer, and then refresh all client configurations. [more recommended]

Above, we choose mode 2. Mode 1 has the following defects:

  • It breaks the single responsibility of microservice, because microservice itself is a business module, and it should not be responsible for configuration refresh
  • Breaking the equivalence of micro service nodes
  • There are certain limitations. For example, when migrating a microservice, its network address often changes. At this time, if you want to update it automatically, you will add more modifications
Implementation of dynamic refresh global broadcast configuration
Modify configuration center

Import pom dependencies

 <!--Add message bus RabbitMQ support-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

Modify yml, application one yml and application two yml needs to be modified as follows:

spring:
  application:
    name: config-center-service
  security:
    # Configure spring security login user name and password
    user:
      name: akieay
      password: configcenter
  #rabbitmq related configuration 15672 is the web management interface port and 5672 is the MQ access port
  rabbitmq:
    host: 192.168.0.163
    port: 5672
    username: guest
    password: guest
    virtual-host: /
  cloud:
    config:
      server:
        git:
          force-pull: true
          uri: https://github. com/admin-strat/springcloud-config. git #github above the git warehouse
          username: xxxxxxx
          password: xxxxxxx
          # search for directory
          search-paths:
            - springcloud-config
      # Read branch
      label: master

# Exposure monitoring endpoint
management:
  endpoints:
    web:
      exposure:
        include: "bus-refresh"

Add configuration class

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

After the modification, restart the service and check whether the service is registered successfully in the registration center.

Modify config client

Import pom dependencies

<!--Add message bus RabbitMQ support-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

Modify yml, also bootstrap one yml and bootstrap two yml needs to be modified as follows:

spring:
  application:
    name: config-client-service
  cloud:
    config:
#      uri: http://localhost:3344 # configuration center address
      label: master  #Branch name
      name: config  #Profile name
      profile: dev  #Read the suffix name and the above three combinations: the configuration file of config-dev.yml on the master branch is read
      username: akieay
      password: configcenter
      discovery:
        enabled: true
        service-id: CONFIG-CENTER-SERVICE
  #rabbitmq related configuration 15672 is the web management interface port and 5672 is the MQ access port
  rabbitmq:
    host: 192.168.0.163
    port: 5672
    username: guest
    password: guest
    virtual-host: /

# Exposure monitoring endpoint
management:
  endpoints:
    web:
      exposure:
        include: "*"

Business modification

@RestController
@RefreshScope
public class ConfigClientController {

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

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/configInfo")
    public String getConfigInfo(){
        return "serverPort: "+port + "\t configInfo: " +configInfo;
    }
}

Restart the service and check the service registration in the registration center.

Dynamic refresh global broadcast

After starting all the services, we can log in to the RabbitMQ console and find that Spring Cloud Bus has created a switch called springCloudBus and four spring cloudbuses in the form of queue Queues starting with anonymous:

Next, we will demonstrate in detail how to dynamically refresh the global broadcast, and you can view the relevant information on the RabbitMQ console.

1, Visit github to view the configuration information of config-dev.yml

2, And visit: http://localhost:3344/master/config-dev.yml , http://localhost:3345/master/config-dev.yml, http://localhost:3355/configInfo , http://localhost:3356/configInfo Check whether the configuration information can be obtained normally.


3, Modify the configuration information of config-dev.yml on github and modify the version number;

4, Visit at this time: http://localhost:3344/master/config-dev.yml , http://localhost:3345/master/config-dev.yml, http://localhost:3355/configInfo , http://localhost:3356/configInfo It can be found that the 3344 and 3345 configuration centers have updated the configuration information, while the 3355 and 3356 clients have not updated the configuration information.

5, At this point, we use the postman call http://localhost:3344/actuator/bus-refresh, send a post request to the configuration center to trigger the / bus/refresh endpoint of a server ConfigServer using the message bus, and then refresh all client configurations; Note: since we use security to realize the authentication of the configuration center, when refreshing the endpoint of the configuration center, we also need to add the user name and password we set to pass the authentication of security in order to realize the refresh function.

6, View: http://localhost:3355/configInfo , http://localhost:3356/configInfo You can find that the configuration information has been refreshed.

The above is the demonstration of the dynamic refresh global broadcast function. The function of one modification, broadcast notification and effectiveness everywhere is realized by refreshing the configuration center.

Dynamic refresh fixed point notification

In actual work, we may encounter that after modifying the configuration of the configuration center, we do not need to notify all, but only the needs of some services; At this time, the global broadcast described above will no longer be suitable. At this time, we can refresh the specified service node through fixed-point notification.

Simply put, it is to specify a specific instance to take effect instead of all. The specific formula is:

http://Configuration center address [ip+port] / Actor / bus refresh / {destination}
destination: Alias for microservice+port

/The bus/refresh request is not sent to the specific service instance, but to the config server and specifies the service or instance that needs to update the configuration through the destination parameter class

Test fixed point refresh

We use the previous service. Through the above global broadcast demonstration, the current github configuration is:

What we need to demonstrate is that after modifying the github configuration, refresh the config client 3355 and refresh 3356 at the same time; The specific steps are as follows: first, we need to modify the configuration on github, as follows:

Re call: http://localhost:3344/actuator/bus-refresh/CONFIG-CLIENT-SERVICE:3355

see: http://localhost:3355/configInfo And http://localhost:3356/configInfo You can see that 3355 has been updated and 3356 is still the original configuration.


Notification summary:

Tags: Spring Cloud

Posted by FireWhizzle on Sun, 08 May 2022 02:48:16 +0300