Project Instruction

This example illustrates how to use RocketMQ Binder implement pub/sub messages for Spring Cloud applications.

RocketMQ is a distributed messaging and streaming platform with low latency, high performance and reliability, trillion-level capacity and flexible scalability.

Before we start the demo, let’s look at Spring Cloud Stream.

Spring Cloud Stream is a framework for building message-driven microservice applications. Spring Cloud Stream builds upon Spring Boot to create standalone, production-grade Spring applications and uses Spring Integration to provide connectivity to message brokers. It provides opinionated configuration of middleware from several vendors, introducing the concepts of persistent publish-subscribe semantics, consumer groups, and partitions.

There are two concepts in Spring Cloud Stream: Binder 和 Binding.

  • Binder: A strategy interface used to bind an app interface to a logical name.

Binder Implementations includes KafkaMessageChannelBinder of kafka, RabbitMessageChannelBinder of RabbitMQ and RocketMQMessageChannelBinder of RocketMQ.

  • Binding: Including Input Binding and Output Binding.

Binding is Bridge between the external messaging systems and application provided Producers and Consumers of messages.

This is a overview of Spring Cloud Stream.

RocketMQ Example - 图1

Demo

Integration with RocketMQ Binder

Before we start the demo, let’s learn how to Integration with RocketMQ Binder to a Spring Cloud application.

Note: This section is to show you how to connect to Sentinel. The configurations have been completed in the following example, so you don’t need modify the code any more.

  1. Add dependency spring-cloud-starter-stream-rocketmq in the pom.xml file in your Spring Cloud project.
  1. <dependency>
  2. <groupId>com.alibaba.cloud</groupId>
  3. <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
  4. </dependency>
  1. Configure Input and Output Binding and cooperate with @EnableBinding annotation
  1. @SpringBootApplication
  2. @EnableBinding({ Source.class, Sink.class })
  3. public class RocketMQApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(RocketMQApplication.class, args);
  6. }
  7. }

Configure Binding:

  1. # configure the nameserver of rocketmq
  2. spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
  3. # configure the output binding named output
  4. spring.cloud.stream.bindings.output.destination=test-topic
  5. spring.cloud.stream.bindings.output.content-type=application/json
  6. # configure the input binding named input
  7. spring.cloud.stream.bindings.input.destination=test-topic
  8. spring.cloud.stream.bindings.input.content-type=application/json
  9. spring.cloud.stream.bindings.input.group=test-group
  1. pub/sub messages

Download and Startup RocketMQ

You should startup Name Server and Broker before using RocketMQ Binder.

  1. Download RocketMQ and unzip it.

  2. Startup Name Server

  1. sh bin/mqnamesrv
  1. Startup Broker
  1. sh bin/mqbroker -n localhost:9876
  1. Create topic: test-topic
  1. sh bin/mqadmin updateTopic -n localhost:9876 -c DefaultCluster -t test-topic

Start Application

  1. Add necessary configurations to file /src/main/resources/application.properties.
  1. spring.application.name=rocketmq-example
  2. server.port=28081
  1. Start the application in IDE or by building a fatjar.

    1. Start in IDE: Find main class RocketMQApplication, and execute the main method.
    2. Build a fatjar: Execute command mvn clean package to build a fatjar, and run command java -jar rocketmq-example.jar to start the application.

Message Handle

Using the binding named output and sent messages to test-topic topic.

And using two input bindings to subscribe messages.

  • input1: subscribe the message of test-topic topic and consume ordered messages(all messages should in the same MessageQueue if you want to consuming ordered messages).

  • input2: subscribe the message of test-topic topic and consume concurrent messages which tags is tagStr, the thread number in pool is 20 in Consumer side.

see the configuration below:

  1. spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
  2. spring.cloud.stream.bindings.output.destination=test-topic
  3. spring.cloud.stream.bindings.output.content-type=application/json
  4. spring.cloud.stream.bindings.input1.destination=test-topic
  5. spring.cloud.stream.bindings.input1.content-type=text/plain
  6. spring.cloud.stream.bindings.input1.group=test-group1
  7. spring.cloud.stream.rocketmq.bindings.input1.consumer.orderly=true
  8. spring.cloud.stream.bindings.input2.destination=test-topic
  9. spring.cloud.stream.bindings.input2.content-type=text/plain
  10. spring.cloud.stream.bindings.input2.group=test-group2
  11. spring.cloud.stream.rocketmq.bindings.input2.consumer.orderly=false
  12. spring.cloud.stream.rocketmq.bindings.input2.consumer.tags=tagStr
  13. spring.cloud.stream.bindings.input2.consumer.concurrency=20

Pub Messages

Using MessageChannel to send messages:

  1. public class ProducerRunner implements CommandLineRunner {
  2. @Autowired
  3. private MessageChannel output;
  4. @Override
  5. public void run(String... args) throws Exception {
  6. Map<String, Object> headers = new HashMap<>();
  7. headers.put(MessageConst.PROPERTY_TAGS, "tagStr");
  8. Message message = MessageBuilder.createMessage(msg, new MessageHeaders(headers));
  9. output.send(message);
  10. }
  11. }

Or you can using the native API of RocketMQ to send messages:

  1. public class RocketMQProducer {
  2. DefaultMQProducer producer = new DefaultMQProducer("producer_group");
  3. producer.setNamesrvAddr("127.0.0.1:9876");
  4. producer.start();
  5. Message msg = new Message("test-topic", "tagStr", "message from rocketmq producer".getBytes());
  6. producer.send(msg);
  7. }

Sub Messages

Using @StreamListener to receive messages:

  1. @Service
  2. public class ReceiveService {
  3. @StreamListener("input1")
  4. public void receiveInput1(String receiveMsg) {
  5. System.out.println("input1 receive: " + receiveMsg);
  6. }
  7. @StreamListener("input2")
  8. public void receiveInput2(String receiveMsg) {
  9. System.out.println("input2 receive: " + receiveMsg);
  10. }
  11. }

Endpoint

Add dependency spring-cloud-starter-stream-rocketmq to your pom.xml file, and configure your endpoint security strategy.

  • Spring Boot1.x: Add configuration management.security.enabled=false
  • Spring Boot2.x: Add configuration management.endpoints.web.exposure.include=*

To view the endpoint information, visit the following URLS:

Endpoint will metrics some data like last send timestamp, sending or receive message successfully times or unsuccessfully times.

  1. {
  2. "runtime": {
  3. "lastSend.timestamp": 1542786623915
  4. },
  5. "metrics": {
  6. "scs-rocketmq.consumer.test-topic.totalConsumed": {
  7. "count": 11
  8. },
  9. "scs-rocketmq.consumer.test-topic.totalConsumedFailures": {
  10. "count": 0
  11. },
  12. "scs-rocketmq.producer.test-topic.totalSentFailures": {
  13. "count": 0
  14. },
  15. "scs-rocketmq.consumer.test-topic.consumedPerSecond": {
  16. "count": 11,
  17. "fifteenMinuteRate": 0.012163847780107841,
  18. "fiveMinuteRate": 0.03614605351360527,
  19. "meanRate": 0.3493213353657594,
  20. "oneMinuteRate": 0.17099243039490175
  21. },
  22. "scs-rocketmq.producer.test-topic.totalSent": {
  23. "count": 5
  24. },
  25. "scs-rocketmq.producer.test-topic.sentPerSecond": {
  26. "count": 5,
  27. "fifteenMinuteRate": 0.005540151995103271,
  28. "fiveMinuteRate": 0.01652854617838251,
  29. "meanRate": 0.10697493212602836,
  30. "oneMinuteRate": 0.07995558537067671
  31. },
  32. "scs-rocketmq.producer.test-topic.sentFailuresPerSecond": {
  33. "count": 0,
  34. "fifteenMinuteRate": 0.0,
  35. "fiveMinuteRate": 0.0,
  36. "meanRate": 0.0,
  37. "oneMinuteRate": 0.0
  38. },
  39. "scs-rocketmq.consumer.test-topic.consumedFailuresPerSecond": {
  40. "count": 0,
  41. "fifteenMinuteRate": 0.0,
  42. "fiveMinuteRate": 0.0,
  43. "meanRate": 0.0,
  44. "oneMinuteRate": 0.0
  45. }
  46. }
  47. }

Note: You should add metrics-core dependency if you want to see metrics data. endpoint will show warning information if you don’t add that dependency:

  1. {
  2. "warning": "please add metrics-core dependency, we use it for metrics"
  3. }

More

For more information about RocketMQ, see RocketMQ Project.

If you have any ideas or suggestions for Spring Cloud RocketMQ Binder, please don’t hesitate to tell us by submitting github issues.