1、单向消息
只发送消息,不等待服务器响应,只发送请求不等待应答。此方式发送消息的过程耗时非常短,一般在微秒级别。
public class Producer {
public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
DefaultMQProducer producer = new DefaultMQProducer("xxoo");
//设置name server地址
producer.setNamesrvAddr("192.168.244.8:9876");
producer.start();
// topic 消息将要发送的地址
// body 消息中具体的数据
Message msg = new Message("myTopic001", "hello1".getBytes());
/**
* 只发送消息,不等待服务器响应,只发送请求不等待应答。
* 此方式发送消息的过程耗时非常短,一般在微秒级别。
*/
producer.sendOneway(msg);
producer.shutdown();
}
}
2、批量消息
可以多条消息打包一起发送,减少网络传输次数提高效率。
`producer.send(Collection c) `方法可以接受一个集合 实现批量发送
-
批量消息要求必要具有同一topic、相同消息配置
-
不支持延时消息
-
建议一个批量消息最好不要超过1MB大小
-
如果不确定是否超过限制,可以手动计算大小分批发送
public class Producer {
public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
DefaultMQProducer producer = new DefaultMQProducer("xxoo");
//设置name server地址
producer.setNamesrvAddr("192.168.244.8:9876");
producer.start();
// topic 消息将要发送的地址
// body 消息中具体的数据
Message msg1 = new Message("myTopic001", "hello1".getBytes());
Message msg2 = new Message("myTopic001", "hello2".getBytes());
Message msg3 = new Message("myTopic001", "hello3".getBytes());
//同步消息发送
ArrayList<Message> messages = new ArrayList<>();
messages.add(msg1);
messages.add(msg2);
messages.add(msg3);
//发送多条消息(批量发送)
/**
* - 批量消息要求必要具有同一topic、相同消息配置
* - 不支持延时消息
* - 建议一个批量消息最好不要超过1MB大小
* - 如果不确定是否超过限制,可以手动计算大小分批发送
*/
SendResult sendResult = producer.send(messages);
System.out.println("sendResult:" + sendResult);
producer.shutdown();
}
}
3、消费消息
public class Consumer {
public static void main(String[] args) throws MQClientException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("ooxx");
consumer.setNamesrvAddr("192.168.244.8:9876");
//每个consumer关注一个topic
//topic 关注的消息地址
//过滤器 * 表示不过滤
consumer.subscribe("myTopic001", "*");
//注册监听器
consumer.registerMessageListener(new MessageListenerConcurrently(){
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
list.forEach(message -> {
byte[] body = message.getBody();
System.out.println(new String(body));
});
// 返回一个消费状态 CONSUME_SUCCESS:消费成功 RECONSUME_LATER:稍后重新推送消费
// 默认情况下 只会被一个consumer消费到 点对点消费
// ack -> acknowledge
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
consumer.start();
}
}