简介:Springboot2.x整合RocketMQ4.x实战,加入相关依赖,开发生产者代码
先启动nameser和broker,命令如下
start mqnamesrv.cmd和start mqbroker.cmd -n 127.0.0.1:9876 autoCreateTopicEnable=true
1、加入相关依赖
<!-- 整合消息队列RocketMQ -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-common</artifactId>
<version>4.6.0</version>
</dependency>
2、application.properties加入配置文件
#rocketMQ配置
#消费者的组名
apache.rocketmq.consumer.PushConsumer=orderConsumer
#生产者的组名
apache.rocketmq.producer.producerGroup=Producer
#NameServer地址
apache.rocketmq.namesrvAddr=127.0.0.1:9876
3、开发MsgProducer
package net.xdclass.base_project.jms;
import javax.annotation.PostConstruct;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 生产者
* @author wq
*
*/
@Component
public class MsgProducer {
/**
* 生产者的组名
*/
@Value("${apache.rocketmq.producer.producerGroup}")
private String producerGroup;//名称为配置文件中的名字
/**
* NameServer地址
*/
@Value("${apache.rocketmq.namesrvAddr}")
private String namesrvAddr;//名称为配置文件中的名字
private DefaultMQProducer producer;
public DefaultMQProducer getProducer(){
return this.producer;
}
/**
* 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,
* 并且只会被服务器调用一次,类似于Serclet的inti()方法。
* 被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
*/
@PostConstruct
public void defaultMQProducer(){
//生产者的组名
producer = new DefaultMQProducer(producerGroup);
//指定NameServer地址,多个地址以 ; 隔开
//如 producer.setNamesrvAddr("192.168.100.141:9876;192.168.100.142:9876;192.168.100.149:9876");
producer.setNamesrvAddr(namesrvAddr);
producer.setVipChannelEnabled(false);
try{
//Producer对象在使用之前必须要调用start初始化,只能初始化一次
producer.start();
}catch(Exception e){
e.printStackTrace();
}
//producer.shutdown(); 一般在应用上下文,关闭的时候进行关闭,用上下文监听器
}
}
控制器,发送消息到borker
//rocketMQ测试
@Autowired
private MsgProducer msgProducer;
/**
* 功能描述:微信支付回调接口
* @param msg 支付信息
* @param tag 消息二级分类
* @return
*/
@GetMapping("/order1")
public Object order(String msg, String tag) throws MQClientException, RemotingException, MQBrokerException, InterruptedException, UnsupportedEncodingException{
/**
* 创建一个消息实例,包含 topic、tag 和 消息体
*/
Message message = new Message("testTopic",tag, msg.getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult result = msgProducer.getProducer().send(message);
System.out.println("发送响应:MsgId:" + result.getMsgId() + ",发送状态:" + result.getSendStatus());
return JsonData.buildSuccess();
}
访问浏览器
成功后会将信息存放于broker,控制台打印如下
发送响应:MsgId:00000000000000000000000000000001000073D16E931C2B19120000,发送状态:SEND_OK
----------------------------------消费者如下----------------------------------------------
package net.xdclass.base_project.jms;
import javax.annotation.PostConstruct;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 消费者
* @author wq
*/
@Component
public class MsgConsumer {
/**
* 消费者的组名
*/
@Value("${apache.rocketmq.consumer.PushConsumer}")
private String consumerGroup;//名称为配置文件中的名字
/**
* NameServer地址
*/
@Value("${apache.rocketmq.namesrvAddr}")
private String namesrvAddr;//名称为配置文件中的名字
@PostConstruct
public void defaultMQPushConsumer(){
//消费者的组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerGroup);
//指定NameServer地址,多个地址以 ; 隔开
consumer.setNamesrvAddr(namesrvAddr);
try{
//设置consumer所订阅的Topic和Tag,*代表全部的Tag
consumer.subscribe("testTopic", "*");
//CONSUME_FROM_LAST_OFFSET 默认策略,从该队列最尾开始消费,跳过历史消息
//CONSUME_FROM_FIRST_OFFSET 从队列最开始开始消费,即历史消息(还储存在broker的)全部消费一遍
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
//MessageListenerOrderly 这个是有序的
//MessageListenerConcurrently 这个是无序的,并行的方式处理,效率高很多
consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {
try {
for (MessageExt messageExt : list) {
System.out.println("messageExt: " + messageExt);//输出消息内容
String messageBody = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
System.out.println("消费响应:msgId : " + messageExt.getMsgId() + ", msgBody : " + messageBody);//输出消息内容
}
} catch (Exception e) {
e.printStackTrace();
return ConsumeConcurrentlyStatus.RECONSUME_LATER; //稍后再试
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; //消费成功
});
consumer.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
当发送请求的时候
控制台输出如下
发送响应:MsgId:00000000000000000000000000000001000073D16E933B2179A80001,发送状态:SEND_OK
messageExt: MessageExt [queueId=2, storeSize=218, queueOffset=0, sysFlag=0, bornTimestamp=1581478449576, bornHost=/192.168.1.107:14449, storeTimestamp=1581478449579, storeHost=/192.168.1.107:10911, msgId=C0A8016B00002A9F00000000000001AB, commitLogOffset=427, bodyCRC=73139620, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='testTopic', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=1, CONSUME_START_TIME=1581478449588, UNIQ_KEY=00000000000000000000000000000001000073D16E933B2179A80001, CLUSTER=DefaultCluster, WAIT=true, TAGS=pay}, body=[120, 100, 99, 108, 97, 115, 115, 56, 56, 56], transactionId='null'}]
消费响应:msgId : 00000000000000000000000000000001000073D16E933B2179A80001, msgBody : xdclass888
注意事项:
问题:
1、Caused by: org.apache.rocketmq.remoting.exception.RemotingConnectException: connect to <172.17.42.1:10911> failed
2、com.alibaba.rocketmq.client.exception.MQClientException: Send [1] times, still failed, cost [1647]ms, Topic: TopicTest1, BrokersSent: [broker-a, null, null]
3、org.apache.rocketmq.client.exception.MQClientException: Send [3] times, still failed, cost [497]ms, Topic: TopicTest, BrokersSent: [chenyaowudeMacBook-Air.local, chenyaowudeMacBook-Air.local, chenyaowudeMacBook-Air.local]
解决:多网卡问题处理
1、设置producer: producer.setVipChannelEnabled(false);
2、编辑ROCKETMQ 配置文件:broker.conf(下列ip为自己的ip)
namesrvAddr = 192.168.0.101:9876
brokerIP1 = 192.168.0.101
4、DESC: service not available now, maybe disk full, CL:
解决:修改启动脚本runbroker.sh,在里面增加一句话即可:
JAVA_OPT="${JAVA_OPT} -Drocketmq.broker.diskSpaceWarningLevelRatio=0.98"
(磁盘保护的百分比设置成98%,只有磁盘空间使用率达到98%时才拒绝接收producer消息)
常见问题处理:
https://blog.csdn.net/sqzhao/article/details/54834761
https://blog.csdn.net/mayifan0/article/details/67633729
https://blog.csdn.net/a906423355/article/details/78192828