RocketMQ练习

本文详细介绍了RocketMQ的使用,包括如何创建生产者(Producer)发送消息,以及如何设置消费者(Consumer)接收并处理这些消息,是学习Apache RocketMQ的基础教程。
摘要由CSDN通过智能技术生成

生产者(Producer)

package org.rocketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import javax.security.auth.callback.Callback;
import java.util.ArrayList;
import java.util.List;


public class RocketMQProducer {


    /**
     * 1.1普通消息发送之同步消息发送
     */

    private static void sendSyncMessage() throws MQClientException, RemotingException, InterruptedException, MQBrokerException {

        // 实例化一个producer对象 && 设置生产者组
        DefaultMQProducer producer = new DefaultMQProducer("Study");

        // 设置MQ的nameServer的地址
        producer.setNamesrvAddr("172.17.0.2:9876");

        // 开始producer发送消息
        producer.start();

//        // 1.1 以单条消息为粒度发送100条消息体为: this is test message of normal & sync & single : number of xxx;
//
//        // 获取message对象
//
//        Message message ;
//
//        for (int i = 1; i <= 100; i++) {
//
//            // 创建消息对象 参数:Topic:TopicOneTest tags:normal & sync & single body:this is test message of normal & sync & single : number of xxx
//            message = new Message("TopicOneTest","normal & sync & single",("this is test message of normal & sync & single : number of " + i).getBytes());
//
//            // 发送消息
//            producer.send(message);
//        }
        // 1.2 以10条记录为一批次发送400~499的共计100条消息,消息体为: this is test message of nomal & sync & batch : number of xxx;
        // 批量消息的大小不能超过 1MiB && 同一批 batch 中 topic 必须相同

        // 创建List对象
        List<Message> msgList = new ArrayList<Message>();


        for (int i = 400; i < 500; i++) {

            // 往消息列表中添加消息
            msgList.add(new Message("TopicOneTest", "normal & sync & batch", ("this is test message of normal & sync & batch : number of " + i).getBytes()));

            // 判断如果消息为某一批次的最后一个元素,则发送消息并且清空消息列表
            if (i % 10 == 9) {

                // 发送消息
                producer.send(msgList);

                // 清空消息列表
                msgList.clear();
            }
        }

        // 关闭producer
        producer.shutdown();


    }

    /**
     * 1.2普通消息之异步消息发送
     */

    private static void sendAsyncMessage() throws MQClientException, RemotingException, InterruptedException, MQBrokerException {

        // 实例化一个生产者
        DefaultMQProducer producer = new DefaultMQProducer("Study");

        // 设置nameService地址
        producer.setNamesrvAddr("172.17.0.2:9876");

        // 开始生产者
        producer.start();

        // 设置发送失败重试次数
        producer.setRetryTimesWhenSendAsyncFailed(0);


        // 批量发送消息,从200到299,消息体为 : this is test message of normal & async & single : number of xxx
        for (int i = 200; i < 300; i++) {

            // 发送异步消息
            producer.send(new Message("TopicOneTest", "normal & async & single", ("this is test message of normal & async & single : number of " + i).getBytes()), new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {

                    // 返回结果发送成功了需要做什么事情
                    System.out.println(sendResult.getMsgId() + " : " + "消息消息发送成功了");

                }

                @Override
                public void onException(Throwable throwable) {

                    // 返回结果发送异常了做什么事情
                    System.out.println(throwable);


                }
            });

        }

        // 尝试使用批量发送方式
        // !!! 异步发送只支持单条发送


        // 并不能结束生产者

//        producer.shutdown();

    }

    /**
     * 单向发送
     */

    private static void sendOneWayMessage() throws MQClientException, RemotingException, InterruptedException {

        // 实例化生产者对象

        DefaultMQProducer producer = new DefaultMQProducer("Study");

        // 设置NameServer的地址
        producer.setNamesrvAddr("172.17.0.2:9876");

        // 生产者开始发送消息
        producer.start();

        // 发送666到888的消息: 大江东去浪淘尽,奔流到海不复回:xxx

        for (int i = 10000000; i <= 10000900; i++) {

            producer.sendOneway(new Message("TopicOneTest", "normal & oneWay & single", ("大江东去浪淘尽,奔流到海不复回:" + i).getBytes()));

            System.out.println("Test" + i);
        }

        // 测试能不能停止

        producer.shutdown();

    }


    /**
     * 2.顺序消息
     *   顺序消息的实现是通过相同的key发送到相同的分区(queue)中
     */

    private static void sendMessageOrder() throws MQClientException, RemotingException, InterruptedException, MQBrokerException {

        // 实例化一个生产者
        DefaultMQProducer producer = new DefaultMQProducer("Study");

        // 设置nameServer的地址
        producer.setNamesrvAddr("172.17.0.2:9876");

        // 开始发送消息
        producer.start();


        Message msg;

        for (int i = 1000; i < 1100; i++) {

            //构建消息对象
            msg = new Message("TopicOneTest","order & single",("this is a message of order : num of " + i).getBytes());

            // 发送消息(根据订单ID发送到不同的队列里) // 认为i为订单编号
            producer.send(msg, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {

                    // 实现队列选择器
                    // 根据订单ID决定分发到主题中的那个队列里(分区)

                    int orderId = (int)o; // 将订单ID转化为整数型

                    return list.get(orderId % list.size());
                }
            }, i);
        }

        // 关闭连接
        producer.shutdown();

    }


    /**
     * 3.消息延迟发送
     * */

    private static void sendMessageDelay() throws MQClientException, RemotingException, InterruptedException, MQBrokerException {

        // 实例化生产者对象
        DefaultMQProducer producer = new DefaultMQProducer("Study");

        // 设置nameServer
        producer.setNamesrvAddr("172.17.0.2:9876");

        // 发送消息
        producer.start();

        Message msg;

        for (int i = 1700; i < 1800; i++) {

            msg = new Message("TopicOneTest","delay & single",("this is a message of delay : number is " + i).getBytes());

            if (i % 3 == 0){
                // 设置消息延迟登记
                msg.setDelayTimeLevel(4);
            }
            producer.send(msg);
        }


        producer.shutdown();

    }


    /**
     * 4.事务消息发送(暂未实践)
     * */

    private static void sendMessageTransaction(){

        // 实现接口
        TransactionListener transactionListener = new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                return null;
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                return null;
            }
        };

    }

    /**
     * 5.发送属性消息
     * */

    private static void sendPropertyMessage() throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        // 实例化生产者
        DefaultMQProducer producer = new DefaultMQProducer("Study");

        // 设置nameServer
        producer.setNamesrvAddr("172.17.0.2:9876");

        // 实例化消息

        producer.start();

        Message message = new Message("TopicOneTest","Tag-A","This is message send by whh on 20201007, is used by Test!!".getBytes());
        message.putUserProperty("user","whh");
        message.putUserProperty("time","20221007");
        message.putUserProperty("use","Test");

        producer.send(message);




        producer.shutdown();

    }

    public static void main(String[] args) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {

        // System.out.println("hello world");

        // 普通消息 之 同步消息发送
//        sendSyncMessage();


        // 普通消息之异步消息发送
//        sendAsyncMessage();

        // 发送单向消息
//        sendOneWayMessage();

        // 发送顺序消息

//        sendMessageOrder();

        // 发送延迟消息
//        sendMessageDelay();

        sendPropertyMessage();
    }
}

消费者(Consumer)

package org.rocketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

public class RocketMQConsumer {

    /**
     * 1.push消费之并发消费
     *
     * */

    private static void pushConsumeConcurrency() throws MQClientException {

        // 实例化一个消费者

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("Study004");

        // 设置nameServer的地址
        consumer.setNamesrvAddr("172.17.0.2:9876");

        // 设置消费者模式: 分为广播模式和集群模式
//        consumer.setMessageModel(MessageModel.CLUSTERING); // 默认为:CLUSTERING


        // 订阅一个Topic
        consumer.subscribe("TopicOneTest","order & single||delay & single");



        // 注册监听器
        consumer.registerMessageListener((MessageListenerConcurrently) (msgList, consumeConcurrentlyContext) -> {
            for (MessageExt msg : msgList) {

                System.out.println(new String(msg.getBody()));
            }

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        // 读取消息

        consumer.start();
        // 关闭连接

    }




    /**
     * 2.push消费之顺序消费
     * */

    private static void pushConsumeOrderly() throws MQClientException {

        // 注册消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("Study1234");

        // 设置nameServer
        consumer.setNamesrvAddr("172.17.0.2:9876");

        // 设置消费模式为集群
//        consumer.setMessageModel(MessageModel.CLUSTERING);

        // 订阅topic
        consumer.subscribe("TopicOneTest","order & single||delay & single");

        //注册监听器
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgList, ConsumeOrderlyContext consumeOrderlyContext) {

                for (MessageExt msg : msgList) {
                    System.out.println(new String(msg.getBody()));
                }

                return ConsumeOrderlyStatus.SUCCESS;
            }
        });

        consumer.start();



    }



    /**
     * 3.消息过滤
     *
     * */

    private static void filterMessage() throws MQClientException {

        // 实例化一个消费之
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("Study_whh");

        // 设置nameServer
        consumer.setNamesrvAddr("172.17.0.2:9876");

        // 设置消费者模式
        // consumer.setMessageModel(MessageModel.CLUSTERING);

        // 订阅Topic
        consumer.subscribe("TopicOneTest", MessageSelector.bySql("user = 'whh' and time = '20221007'"));



        // 注册监听器
        consumer.registerMessageListener((MessageListenerConcurrently) (list, consumeConcurrentlyContext) -> {
            for (MessageExt msg : list) {
                System.out.print(System.currentTimeMillis());
                System.out.println(new String(msg.getBody()));
            }

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        // 开始消费
        consumer.start();



    }


    /**
     * 4.pull消费 之 Pull Consumer
     * */


    /**
     * 5.pull消费 之 Lite Pull Consumer
     * */
    public static void main(String[] args) throws MQClientException {

//        pushConsumeOrderly();

        filterMessage();
    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值