注意:1、安装的MQ版本要和代码依赖的版本一致 例如本例安装的MQ 4.7.0 代码依赖如下也要是4.7.0
<!-- RocketMQ --> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>4.7.0</version> </dependency> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-all</artifactId> <version>4.7.0</version> <type>pom</type> </dependency>
2、groupId低版本的是
com.alibaba.rocketmq
高版本的是
org.apache.rocketmq
生产者
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
public class Producer {
public static void main(String[] args) {
DefaultMQProducer producer = new DefaultMQProducer("XXXProducer");
producer.setNamesrvAddr("******:9876");
try {
producer.start();
String pushMsg="37000021222;233333;90;20";
Message msg = new Message("InvoiceTopic","useInvoice","1",
pushMsg.getBytes("UTF-8"));
SendResult result = producer.send(msg);
System.out.println("id:" + result.getMsgId() +
" result:" + result.getSendStatus());
String pushMsg2="37000021222;23333344;290;20";
msg = new Message("InvoiceTopic","useInvoice","2",pushMsg2.getBytes("UTF-8"));
result = producer.send(msg);
System.out.println("id:" + result.getMsgId() +
" result:" + result.getSendStatus());
String pushMsg3="37000021222;23533344;390;20";
msg = new Message("InvoiceTopic","releaseInvoice","1",pushMsg3.getBytes());
result = producer.send(msg);
System.out.println("id:" + result.getMsgId() +
" result:" + result.getSendStatus());
} catch (Exception e) {
e.printStackTrace();
} finally {
producer.shutdown();
}
}
}
消费者PUSH
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("MMTTconsumerGroupName");
// 设置服务器地址
consumer.setNamesrvAddr("*****:9876");
// 订阅指定主题
consumer.subscribe("InvoiceTopic","useInvoice");
// 注册消息监听事件
consumer.registerMessageListener(new MessageListenerConcurrently() {
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
try {
for (MessageExt msg: msgs) {
String recString = new String(msg.getBody() ,"UTF-8");
System.out.println(recString);
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}catch (Exception e){
e.printStackTrace();
}
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
});
// 启动消费者
consumer.start();
}
}
来源:oschina
链接:https://my.oschina.net/u/4086064/blog/4458810