RocketMQ发送消息和消费消息
一、使用前配置
1 配置ROCKETMQ_HOME到系统环境变量中,因为启动脚本会读取这个变量
2 进入bin目录,用编辑器打开红色标注的脚本
3 查看内容,发现每个脚本会调用另外一个脚本,最终要修改如下的脚本
打开之后找到这一行,修改成红色标注的一样
其实就是把2g改为1g,防止内存设置过大而导致的其他问题
二、启动命令
4 分别进入bin目录下 启动如下脚本:
& 启动namesrv
& 启动brokerserver
看到如下就代表两个服务都成功启动了
三、pom.xml文件配置
看一下pom.xml的文件内容
<?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.suning.mq</groupId>
<artifactId>rocketmq</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
</dependencies>
</project>
四、编码
4.1 先定义一个消息保存的载体:
package producer;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import java.io.Serializable;
/**
* @Author 18011618
* @Date 10:41 2018/7/17
* @Function 消息生产者
*/
public class Producer {
public static void main(String[] args) throws MQClientException {
DefaultMQProducer producer = new DefaultMQProducer("test-group");
producer.setNamesrvAddr("localhost:9876");
producer.setInstanceName("rmq-instance");
producer.start();
try {
for (int i=0;i<100;i++){
User user = new User();
user.setLoginName("abc"+i);
user.setPwd(String.valueOf(i));
Message message = new Message("log-topic", "user-tag",JSON.toJSONString(user).getBytes());
System.out.println("生产者发送消息:"+JSON.toJSONString(user));
producer.send(message);
}
} catch (Exception e) {
e.printStackTrace();
}
producer.shutdown();
}
/**
* 发送用户消息
*/
static class User implements Serializable{
private String loginName;
private String pwd;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
4.2 定义消息的发送者:
package com.springboot.rocketmq.one.producer;
import com.alibaba.fastjson.JSON;
import com.springboot.rocketmq.content.UserContent;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* @Author 18011618
* @Date 10:31 2018/7/18
* @Function 模拟用户消息发送
*/
@Component
public class UserProducer {
/**
* 生产者的组名
*/
@Value("${suning.rocketmq.producerGroup}")
private String producerGroup;
/**
* NameServer 地址
*/
@Value("${suning.rocketmq.namesrvaddr}")
private String namesrvAddr;
@PostConstruct
public void produder() {
DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
producer.setNamesrvAddr(namesrvAddr);
try {
producer.start();
for (int i = 0; i < 100; i++) {
UserContent userContent = new UserContent(String.valueOf(i),"abc"+i);
String jsonstr = JSON.toJSONString(userContent);
System.out.println("发送消息:"+jsonstr);
Message message = new Message("user-topic", "user-tag", jsonstr.getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult result = producer.send(message);
System.err.println("发送响应:MsgId:" + result.getMsgId() + ",发送状态:" + result.getSendStatus());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
producer.shutdown();
}
}
}
4.3 定义消息的消费者:
package 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.message.MessageExt;
import java.util.List;
public class Consumer {
public static void main(String[] args) throws MQClientException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("test-group");
consumer.setNamesrvAddr("localhost:9876");
consumer.setInstanceName("rmq-instance");
consumer.subscribe("log-topic", "user-tag");
consumer.registerMessageListener(new MessageListenerConcurrently() {
public ConsumeConcurrentlyStatus consumeMessage(
List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
System.out.println("消费者消费数据:"+new String(msg.getBody()));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
consumer.start();
}
}
接下来先启动消费者,然后再启动生产者,看一下效果
1.生产者控制台发送消息:
2.消费者控制台消费消息
且能发现消费消息的机制 默认是乱序的
五 RocketMQ Web启动
上面虽然成功了发送了消息和消费了消息,可惜都是通过控制台查看的,其实rocketmq有扩展的组件,其中有一个组件就是支持web界面查看消息相关的功能,下面就简单介绍一下如何使用这个功能:访问 https://github.com/apache/rocketmq-externals/ 可以看到如下界面,选择红色标注的模块,下载到本地:
然后进行部署,它是一个完整的springboot项目,所以可以用IDEA打开
然后需要修改application.properties的相关内容
server.contextPath=
server.port=8080
#spring.application.index=true
spring.application.name=rocketmq-console
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
logging.config=classpath:logback.xml
#if this value is empty,use env value rocketmq.config.namesrvAddr NAMESRV_ADDR | now, you can set it in ops page.default localhost:9876
rocketmq.config.namesrvAddr=localhost:9876
#if you use rocketmq version < 3.5.8, rocketmq.config.isVIPChannel should be false.default true
rocketmq.config.isVIPChannel=
#rocketmq-console's data path:dashboard/monitor
rocketmq.config.dataPath=/tmp/rocketmq-console/data
#set it false if you don't want use dashboard.default true
rocketmq.config.enableDashBoardCollect=true
其实主要就是这个地址,然后启动App这个类,这个时候在浏览器端访问 http://localhost:8080/ 会出现如下界面
点击Dashboard可以查看相关消息主题的信息
还可以查看具体的发送消息和消费消息:点击Message
点击Detail 能看查看消息具体的消息
这个控制台的功能还是很强大的,都可以去摸索一下如何使用.
六SpringBoot和RocketMQ整合
整合方式有很多种,但是可以总结为两大类,一类是基于高度封装(使用起来非常简单,通用性高),一类是基于原始开发(没啥可通用性),在这里把这两个类别都讲解一下.
& 先讲一种,基于原始API开发,不要啥封装,只需要引入一个配置文件即可
看一下整体项目结构,主要实现的部分是红色标注的,其它类是第二种封装使用的,
看一下pom.xml的文件内容
<?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