基于《RocketMQ学习(二):基于Docker镜像搭建单机版》构建的镜像,进行SpringBoot与RocketMQ简单测试。
环境版本:
- SpringBoot 1.5.9
- RocketMQ 4.2.0
- Maven 3.3.9
- Java 1.8
目录大纲:
- (1) 新建project以及添加依赖包
- (2) 启动类App.java
- (3) application配置文件
- (4) logback.xml
- (5) 生产者
- (6) 消费者
- (7) 测试
1、新建project以及添加依赖包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xusg</groupId>
<artifactId>study-rocketmq</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>study-rocketmq</name>
<url>http://maven.apache.org</url>
<description>RocketMQ 学习</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java_source_version>1.8</java_source_version>
<java_target_version>1.8</java_target_version>
<file_encoding>UTF-8</file_encoding>
<springboot.version>1.5.9.RELEASE</springboot.version>
<rocketmq.version>4.2.0</rocketmq.version>
</properties>
<dependencies>
<!--SpringBoot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${springboot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${springboot.version}</version>
<scope>test</scope>
</dependency>
<!--Rocketmq-->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>${rocketmq.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<fork>true</fork>
<source>${java_source_version}</source>
<target>${java_target_version}</target>
<encoding>${file_encoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、启动类App.java
package com.xusg.study;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @Author Xusg
* @Date 18/2/5 16:39
*/
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.xusg.study"})
public class RocketMQApplicationMain {
public static void main(String[] args) {
SpringApplication.run(RocketMQApplicationMain.class, args);
}
}
3、application配置文件
spring:
rocketmq:
namesrvaddr: 192.168.56.101:29876
4、logback.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="10 seconds">
<!--STDOUT LOG-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
<!--日期 线程名 日志级别 类名 程序信息 换行-->
[%date{MM-dd HH:mm:ss SSS}] %thread %level %logger{0} - %msg%n
</pattern>
<charset>UTF-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
</appender>
<!--FILE LOG-->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>
[%date{MM-dd HH:mm:ss SSS}] %thread %level %logger{0} - %msg%n
</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>./logs/study-rocketmq/detail-rocketmq.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<prudent>true</prudent>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
<appender-ref ref="STDOUT"/>
</root>
</configuration>
5、生产者
package com.xusg.study.producer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* RocketMQ生产者
*
* @Author Xusg
* @Date 18/2/5 17:46
*/
@Component
public class MQProducer {
private static final Logger LOGGER = LoggerFactory.getLogger(MQProducer.class);
@Value("${spring.rocketmq.namesrvAddr}")
private String namesrvAddr;
private final DefaultMQProducer producer = new DefaultMQProducer("TestRocketMQProducer");
/**
* 初始化
*/
@PostConstruct
public void start() {
try {
LOGGER.info("MQ:启动生产者");
producer.setNamesrvAddr(namesrvAddr);
producer.start();
} catch (MQClientException e) {
LOGGER.error("MQ:启动生产者失败:{}-{}", e.getResponseCode(), e.getErrorMessage());
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* 发送消息
*
* @param data 消息内容
* @param topic 主题
* @param tags 标签
* @param keys 唯一主键
*/
public void sendMessage(String data, String topic, String tags, String keys) {
try {
byte[] messageBody = data.getBytes(RemotingHelper.DEFAULT_CHARSET);
Message mqMsg = new Message(topic, tags, keys, messageBody);
producer.send(mqMsg, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
LOGGER.info("MQ: 生产者发送消息 {}", sendResult);
}
@Override
public void onException(Throwable throwable) {
LOGGER.error(throwable.getMessage(), throwable);
}
});
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
@PreDestroy
public void stop() {
if (producer != null) {
producer.shutdown();
LOGGER.info("MQ:关闭生产者");
}
}
}
6、消费者
package com.xusg.study.consumer;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
/**
* RocketMQ消费者
*
* @Author Xusg
* @Date 18/2/5 17:46
*/
@Component
public class MQPushConsumer implements MessageListenerConcurrently {
private static final Logger LOGGER = LoggerFactory.getLogger(MQPushConsumer.class);
@Value("${spring.rocketmq.namesrvAddr}")
private String namesrvAddr;
private final DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("TestRocketMQPushConsumer");
/**
* 初始化
*
* @throws MQClientException
*/
@PostConstruct
public void start() {
try {
LOGGER.info("MQ:启动消费者");
consumer.setNamesrvAddr(namesrvAddr);
// 从消息队列头开始消费
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
// 集群消费模式
consumer.setMessageModel(MessageModel.CLUSTERING);
// 订阅主题
consumer.subscribe("TopicTest", "*");
// 注册消息监听器
consumer.registerMessageListener(this);
// 启动消费端
consumer.start();
} catch (MQClientException e) {
LOGGER.error("MQ:启动消费者失败:{}-{}", e.getResponseCode(), e.getErrorMessage());
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* 消费消息
* @param msgs
* @param context
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
int index = 0;
try {
for (; index < msgs.size(); index++) {
MessageExt msg = msgs.get(index);
String messageBody = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
LOGGER.info("MQ:消费者接收新信息: {} {} {} {} {}", msg.getMsgId(), msg.getTopic(), msg.getTags(), msg.getKeys(), messageBody);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (index < msgs.size()) {
context.setAckIndex(index + 1);
}
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
@PreDestroy
public void stop() {
if (consumer != null) {
consumer.shutdown();
LOGGER.error("MQ:关闭消费者");
}
}
}
7、测试
package com.xusg.study;
import com.xusg.study.producer.MQProducer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* @Author Xusg
* @Date 18/2/6 14:45
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RocketMQApplicationMain.class})
public class TestRocketMQ {
@Resource
private MQProducer mqProducer;
@Test
public void testProducer() {
for (int i = 0; i < 10; i++) {
mqProducer.sendMessage("Hello RocketMQ " + i, "TopicTest",
"TagTest", "Key" + i);
}
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#控制台日志信息
[02-06 15:08:52 500] main INFO MQPushConsumer - MQ:启动消费者
[02-06 15:08:53 622] main INFO MQProducer - MQ:启动生产者
[02-06 15:08:53 988] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB400001, offsetMsgId=C0A8386500002A9F00000000000814BA, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=2], queueOffset=681]
[02-06 15:08:53 989] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB400003, offsetMsgId=C0A8386500002A9F0000000000081638, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=0], queueOffset=678]
[02-06 15:08:53 989] ConsumeMessageThread_4 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB3A0000 TopicTest TagTest Key0 Hello RocketMQ 0
[02-06 15:08:53 989] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB430004, offsetMsgId=C0A8386500002A9F00000000000816F7, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=1], queueOffset=680]
[02-06 15:08:53 990] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB430005, offsetMsgId=C0A8386500002A9F00000000000817B6, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=2], queueOffset=682]
[02-06 15:08:53 990] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB430006, offsetMsgId=C0A8386500002A9F0000000000081875, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=3], queueOffset=682]
[02-06 15:08:53 990] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB430007, offsetMsgId=C0A8386500002A9F0000000000081934, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=0], queueOffset=679]
[02-06 15:08:53 990] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB430008, offsetMsgId=C0A8386500002A9F00000000000819F3, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=1], queueOffset=681]
[02-06 15:08:53 990] NettyClientPublicExecutor_1 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB430009, offsetMsgId=C0A8386500002A9F0000000000081AB2, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=2], queueOffset=683]
[02-06 15:08:53 990] NettyClientPublicExecutor_3 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB400002, offsetMsgId=C0A8386500002A9F0000000000081579, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=3], queueOffset=681]
[02-06 15:08:53 990] NettyClientPublicExecutor_2 INFO MQProducer - MQ: 生产者发送消息 SendResult [sendStatus=SEND_OK, msgId=C0A81E55346018B4AAC21CFFEB3A0000, offsetMsgId=C0A8386500002A9F00000000000813FB, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=1], queueOffset=679]
[02-06 15:08:53 991] ConsumeMessageThread_1 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB400001 TopicTest TagTest Key1 Hello RocketMQ 1
[02-06 15:08:53 990] ConsumeMessageThread_3 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB400002 TopicTest TagTest Key2 Hello RocketMQ 2
[02-06 15:08:53 998] ConsumeMessageThread_2 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB400003 TopicTest TagTest Key3 Hello RocketMQ 3
[02-06 15:08:54 007] ConsumeMessageThread_9 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB430008 TopicTest TagTest Key8 Hello RocketMQ 8
[02-06 15:08:54 010] ConsumeMessageThread_5 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB430005 TopicTest TagTest Key5 Hello RocketMQ 5
[02-06 15:08:54 010] ConsumeMessageThread_6 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB430009 TopicTest TagTest Key9 Hello RocketMQ 9
[02-06 15:08:54 010] ConsumeMessageThread_7 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB430006 TopicTest TagTest Key6 Hello RocketMQ 6
[02-06 15:08:54 011] ConsumeMessageThread_8 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB430004 TopicTest TagTest Key4 Hello RocketMQ 4
[02-06 15:08:54 011] ConsumeMessageThread_10 INFO MQPushConsumer - MQ:消费者接收新信息: C0A81E55346018B4AAC21CFFEB430007 TopicTest TagTest Key7 Hello RocketMQ 7
[02-06 15:09:03 965] Thread-3 INFO MQProducer - MQ:关闭生产者
Disconnected from the target VM, address: '127.0.0.1:52407', transport: 'socket'
[02-06 15:09:03 986] Thread-3 ERROR MQPushConsumer - MQ:关闭消费者