"Spring Cloud" distributed must-learn Springcloud (11)--Message driven Springcloud Stream

Source: Internet
Author: User
Tags event listener string format rabbitmq
First, the preface

In the previous blog, the Springcloud series has largely been introduced. If there is too clear little white, or suggest the first blog to learn from small.

In this blog, Xiao Bai introduces you to a message event-driven framework--spring Cloud Stream. Second, what is Spring Cloud Stream?

The first thing to say is message-driven and event-driven:

Suppose the system is like this: there's a B thing to deal with after a.

Event-driven, tell the program that deals with a thing how to do it, after a thing is done, directly call the program (or interface) that handles B to handle B.

Message driven, finished a thing, put a message in a place, meaning I finished a thing, at this time, processing a program has been bob. As to when, how to deal with B, by another program according to the message to deal with.

The event mode coupling is high, the same module is easy to use, the message mode coupling is low and the cross module is easy to use. Event mode integration Other languages are cumbersome, and message mode integration with other languages is easier. The event is an intrusive design that grabs your main loop; The message is non-intrusive, leaving the user with the freedom to design the main loop.

The Spring Cloud Stream is a framework that enables micro services to have message-driven capabilities. Provides a message-driven mechanism that connects message middleware to message-driven through spring integration. It also provides the personalized automation configuration for message middleware, and introduces three core concepts of publish-subscribe, consumer group and partition. Third, Quick Start 3.1 preparation work

Still the same as the old, is still relying on a blog to organize the content, small series on the previous demo has been uploaded to git, you can download.

Https://github.com/AresKingCarry/SpringCloudDemo

In addition, since it is message driven, it is natural to use message middleware, and so far the spring cloud stream supports only RABBITMQ and Kafuka. Here, small weave continues to use RABBITMQ. 3.2 Message Receiving end

Create a new Springboot project named Stream.

3.3 Adding dependencies on the stream

Because the RABBITMQ is used, add spring-cloud-starter-stream-rabbit.

Spring-cloud-starter-stream-rabbit dependencies are encapsulated by the spring cloud stream for RABBITMQ, which also includes automated configuration of RABBITMQ, For example, the default address of the connection rabbitmq is localhost, the default port is 5672, the default username is guest, the default password is also guest, because our RABBITMQ are all adopted the default configuration, so the configuration can not be modified, can also run. If the small partners need to modify, and the same as the previous article, directly in the application.properties can be modified.

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId> Spring-cloud-starter-stream-rabbit</artifactid>
        </dependency>
3.4 Creating the Receiver

Create a class Sinkrecevier to receive messages sent by 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 (Received message: +payload);
    }

Code Description:

@EnableBinding annotations, binding the message channel. This annotation is used to specify one or more interfaces that define @input or @output annotations.

In the code, we bind the Sink interface through @enablebinding (Sink.class), the Sink interface is the default bound input channel in spring Cloud, in addition to the bound output channel source, There are also processor channels for binding input and output channels. In addition to the interface defined by spring Cloud, we can customize it.

@StreamListener annotation is an event listener that registers the modified method as the data stream on the message middleware, and the attribute value in the annotation corresponds to the listener's name.

In the code, we register with the recipient as the input Message channel processing method, and when the input message channel message is heard, the Receive method runs. 3.7 Modifying the configuration file

In the configuration file, we configure the RABBITMQ address, username, etc. 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 '

which
Cloud.stream.bindings.input.destination:trade
Cloud.stream.bindings.input.contentType: ' Application/json '

Indicates that the queue to listen to is trade, and that the listener data format is JSON. 3.6 Running the project

We run the project, the startup code is the default code, without modification, the direct operation can be

After running, the monitoring platform in MQ will find that there is one more record in the queue, Trade.anonymous.XK5Pb5dZTwSoly1iowTDVQ, this is the queue we are listening to.

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

In the control platform, you will see the information that is printed on the monitor:

So it is simple to achieve the receiver end of the build. Below we carry on the construction of the sending end. 3.7 Set up the sending end

Also we need to build a Springboot project, Streamsend.

3.8 Adding dependencies

Access receiver, add 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 end

Establish 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:

Also used the annotation @enablebinding mentioned above, because the message is to be sent, so the Send interface source is bound.

In addition, there are @inboundchanneladapter annotation, send interface. 3.10 Modifying the configuration file

As with the receiver, binds 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 messages

The startup class is also default and no modification is made. Start the project.

You will see the Receive and send console print out the log.

Iv. Summary

Through this study, found that Springcloud has been using annotations to omit a lot of code, the effect is very good, developers through a simple configuration annotation, can be simple development, the agreement is larger than the configuration.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.