[Top] [Spring Cloud] Distributed must learn springcloud (11) - message-driven SpringCloud Stream

I. Introduction

      In the previous blog, most of the springcloud series have been basically introduced. If there is a novice who understands too much, it is recommended to learn from the first blog of the editor.

      In this blog, Xiaobai introduces a message event-driven framework - Spring Cloud Stream.

2. What is Spring Cloud Stream?

      First of all, let’s talk about message-driven and event-driven:

Suppose the system is like this: after processing A, there is still B to be processed

  • Event-driven, it tells the program that handles the A thing how to do the B thing. After the A thing is processed, the program (or interface) that handles the B thing is directly called to handle the B thing.

  • Message-driven, after processing A, put a message somewhere, which means that I have finished processing A. At this time, the program for processing A has been completed. As for when and how to deal with B, another program handles that message according to that message.

      The event mode has high coupling and is easy to use within the same module; the message mode has low coupling and is easy to use across modules. It is cumbersome to integrate other languages ​​with event mode, and it is easier to integrate message mode with other languages. Events are an intrusive design, occupying your main loop; messages are a non-intrusive design, leaving the user the freedom of how the main loop should be designed.

      Spring Cloud Stream is a framework that enables microservices to have message-driven capabilities. Provides a message-driven mechanism, which connects message middleware through Spring Integration to achieve message-driven. It also provides personalized automatic configuration for message middleware, and introduces three core concepts of publish-subscribe, consumer group and partition.

3. Get started quickly

3.1 Preparations

      It's still the same, still relying on the content organized by the previous blog, the editor has uploaded the demos of the last few times to git, and you can download it yourself.

      https://github.com/AresKingCarry/SpringCloudDemo

      In addition, since it is message-driven, it is natural to use message middleware. So far, spring cloud stream only supports rabbitmq and kafuka. Here, the editor continues to use rabbitmq.

3.2 Message receiver

      Create a new springboot project named stream.

write picture description here

3.3 Add dependency on stream

      Because rabbitmq is used, it is added spring-cloud-starter-stream-rabbit.

      The spring-cloud-starter-stream-rabbit dependency is Spring Cloud Stream’s encapsulation of RabbitMQ, which also includes automatic configuration of RabbitMQ. For example, the default address of the connected RabbitMQ is localhost, the default port is 5672, and the default user name is guest. , the default password is also guest. Since our RabbitMQ uses the default configuration, the configuration here can be left unmodified, and the same can be run. If you need to modify it, you can modify it directly in application.properties as in the previous article.

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

3.4 Creating a Receiver

      Create a class SinkReceiver to receive messages from RabbitMQ:

package com.wl.stream.listener;

import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;

/**
 * Created by Ares on 2018/4/18.
 */
@EnableBinding(Sink.class)
public class SinkRecevier {
    @StreamListener(Sink.INPUT)
    public void receive(Object payload){
        System.out.println("接收到消息:"+payload);
    }
}

      Code description:

      @EnableBindingAnnotation, bind message channel. This annotation is used to specify one or more defined @Inputor @Outputannotated interfaces.

      In the code, we bind the Sink interface through @EnableBinding(Sink.class). The Sink interface is the default binding input channel in Spring Cloud. In addition, there are binding output channels Source and binding inputs. The Processor channel of the output channel. In addition to the interfaces defined by Spring Cloud, we can also customize them.

      The @StreamListener annotation is to register the modified method as an event listener for the data stream on the message middleware. The attribute value in the annotation corresponds to the name of the monitored message channel.

      In the code, we register as the processing method of the input message channel through the receive side. When the message of the input message channel is monitored, the receive method will run.

3.7 Modify the configuration file

      In the configuration file, we need to configure the address, username, etc. of the rabbitmq to be monitored.

server:
  port: 10000
spring:
  rabbitmq:
    host: 192.168.137.16
    port: 5672
    username: admin
    password: admin
  application:
    name: stream
  cloud:
    stream:
      bindings:
        input:
          destination: trade
          contentType: 'application/json'

      其中:
      cloud.stream.bindings.input.destination: trade
      cloud.stream.bindings.input.contentType: ‘application/json’

      It indicates that the queue to be monitored is trade, and the data format to be monitored is json.

3.6 Running the project

      We run the project, the startup code is the default code, no need to modify it, just run it directly

      After running, on the monitoring platform of mq, you will find that there is an additional record in the queue, trade.anonymous.XK5Pb5dZTwSoly1iowTDVQ, which is the queue we are monitoring.

write picture description here

      We click on this queue and send a message in the queue:

write picture description here

      In the control platform, you will see the information printed by the monitor:

write picture description here

      In this way, the construction of the receiving end is simply realized. Next, we will build the sender.

3.7 Build the sender

      Also we need to create a springboot project, streamsend.

write picture description here

3.8 Add dependencies

      Through the receiver, add a dependency on rabbitmq:

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

3.9 Write the code of the sender

      Create a class sender:

package com.wl.streamsend.sender;

import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.integration.annotation.InboundChannelAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Ares on 2018/4/18.
 */
@EnableBinding(Source.class)
public class Sender {
    @InboundChannelAdapter(value = Source.OUTPUT)
    public String timerMessageSource() {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(format);
        return format;
    }
}

      Code description:

      The annotation @EnableBinding mentioned above is also used. Because it is to send a message, the sending interface Source is bound.

      In addition, there is @InboundChannelAdapter annotation, sending interface.

3.10 Modify the configuration file

      Like the receiver, bind the specified queue.

server:
  port: 10001
spring:
  rabbitmq:
    host: 192.168.137.16
    port: 5672
    username: admin
    password: admin
  application:
    name: stream-send
  cloud:
    stream:
      bindings:
        output:
          destination: trade
          contentType: 'application/json'

3.11 Sending a message

      The startup class is also the default and has not been modified. Startup project.

      You will see the receiving and sending consoles print out the logs.

write picture description here

4. Summary

      Through this study, I found that springcloud has used annotations to omit a lot of code, and the effect is very good. Developers can simply develop through simple configuration annotations, and the convention is greater than the configuration.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324892761&siteId=291194637