package com.cj.rocket.base.producer;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import java.util.concurrent.TimeUnit;
/**
* 发送同步消息
*/
public class SyncProducer {
public static void main(String[] args) throws Exception {
//1.创建消息生产者producer,并制定生产者组名
DefaultMQProducer producer = new DefaultMQProducer("group1");
//2.指定Nameserver地址
producer.setNamesrvAddr("192.168.159.128:9876;192.168.159.131:9876");
//3.启动producer
producer.start();
for (int i = 0; i < 10; i++) {
//4.创建消息对象,指定主题Topic、Tag和消息体
/**
* 参数一:消息主题Topic
* 参数二:消息Tag
* 参数三:消息内容
*/
Message msg = new Message("base", "Tag1", ("Hello World" + i).getBytes());
//5.发送消息
SendResult result = producer.send(msg);
//发送状态
SendStatus status = result.getSendStatus();
System.out.println("发送结果:" + result);
//线程睡1秒
TimeUnit.SECONDS.sleep(1);
}
//6.关闭生产者producer
producer.shutdown();
}
}
要发送同步消息,必须先启动NameServer和broker
启动NameServer
nohup
sh
bin/mqnamesrv &
tail
-f
~/logs/rocketmqlogs/namesrv.log
启动
broker
1.
nohup
sh
bin/mqbroker
-n
localhost:9876 &
tail
-f
~/logs/rocketmqlogs/broker.log
2.
nohup sh bin/mqbroker -n localhost:9876 autoCreateTopicEnable=true &
红字意思(允许自动创建Topic,且允许通过手工方式创建Topic,用于No route info of this topic报错)
关闭Broker
sh bin/mqshutdown broker
关闭
NameServer
sh bin/mqshutdown namesrv