美文网首页mq
三、RocketMQ快速开始

三、RocketMQ快速开始

作者: 恨别A鸟惊心 | 来源:发表于2019-03-30 11:21 被阅读0次

    快速开始

    本快速入门指南是在本地计算机上设置RocketMQ消息传递系统以发送和接收消息的详细说明。

    环境要求(版本一定要正确)

    1. 建议使用64位操作系统,Linux / Unix / Mac;
    2. 64位JDK 1.8+;
    3. Maven 3.2.x;
    4. Git的;
    5. 4g +免费磁盘用于Broker服务器

    从发布下载和构建

    单击此处下载4.4.0源代码版本。您也可以从这里下载二进制版本。

    现在执行以下命令来解压缩4.4.0源代码版本并构建二进制工件。

      > unzip rocketmq-all-4.4.0-source-release.zip
      > cd rocketmq-all-4.4.0/
      > mvn -Prelease-all -DskipTests clean install -U
      > cd distribution/target/apache-rocketmq
    
    

    启动Name Server

      > nohup sh bin/mqnamesrv &
      > tail -f ~/logs/rocketmqlogs/namesrv.log
      The Name Server boot success...
    
    

    启动Broker

      > nohup sh bin/mqbroker -n localhost:9876 autoCreateTopicEnable=true &
      > tail -f ~/logs/rocketmqlogs/broker.log 
      The broker[%s, 172.30.30.233:10911] boot success...
    
    

    发送和接收消息

    在发送/接收消息之前,我们需要告诉客户端名称服务器的位置。RocketMQ提供了多种方法来实现这一目标。为简单起见,我们使用环境变量NAMESRV_ADDR

     > export NAMESRV_ADDR=localhost:9876
     > sh bin/tools.sh org.apache.rocketmq.example.quickstart.Producer
     SendResult [sendStatus=SEND_OK, msgId= ...
    
     > sh bin/tools.sh org.apache.rocketmq.example.quickstart.Consumer
     ConsumeMessageThread_%d Receive New Messages: [MessageExt...
    
    

    关机服务器

    > sh bin/mqshutdown broker
    The mqbroker(36695) is running...
    Send shutdown request to mqbroker(36695) OK
    
    > sh bin/mqshutdown namesrv
    The mqnamesrv(36664) is running...
    Send shutdown request to mqnamesrv(36664) OK
    

    简单消息示例

    • 使用RocketMQ以三种方式发送消息:可靠的同步,可靠的异步和单向传输。
    • 使用RocketMQ来使用消息

    1.添加依赖关系

        <dependency>
            <groupId>org.apache.rocketmq</groupId>
            <artifactId>rocketmq-client</artifactId>
            <version>4.4.0</version>
        </dependency>
    
    

    注意:rocketMQ-client的版本号必须和 rocketMQ的服务端的版本号一致,不然可能会导致消息发送不出去

    gradle这个:

    compile 'org.apache.rocketmq:rocketmq-client:4.3.0'
    
    

    2.1同步发送消息

    可靠的同步传输用于广泛的场景,如重要的通知消息,短信通知,短信营销系统等。

    public class SyncProducer {
        public static void main(String[] args) throws Exception {
            //Instantiate with a producer group name.
            DefaultMQProducer producer = new
                DefaultMQProducer("please_rename_unique_group_name");
            // Specify name server addresses.
            producer.setNamesrvAddr("192.168.247.132:9876");
            //Launch the instance.
            producer.start();
            for (int i = 0; i < 100; i++) {
                //Create a message instance, specifying topic, tag and message body.
                Message msg = new Message("TopicTest" /* Topic */,
                    "TagA" /* Tag */,
                    ("Hello RocketMQ " +
                        i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                );
                //Call send message to deliver message to one of brokers.
                SendResult sendResult = producer.send(msg);
                System.out.printf("%s%n", sendResult);
            }
            //Shut down once the producer instance is not longer in use.
            producer.shutdown();
        }
    }
    
    

    2.2异步发送消息

    异步传输通常用于响应时间敏感的业务场景。

    public class AsyncProducer {
        public static void main(String[] args) throws Exception {
            //Instantiate with a producer group name.
            DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
            // Specify name server addresses.
            producer.setNamesrvAddr("192.168.247.132:9876");
            //Launch the instance.
            producer.start();
            producer.setRetryTimesWhenSendAsyncFailed(0);
            for (int i = 0; i < 100; i++) {
                    final int index = i;
                    //Create a message instance, specifying topic, tag and message body.
                    Message msg = new Message("TopicTest",
                        "TagA",
                        "OrderID188",
                        "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                    producer.send(msg, new SendCallback() {
                        @Override
                        public void onSuccess(SendResult sendResult) {
                            System.out.printf("%-10d OK %s %n", index,
                                sendResult.getMsgId());
                        }
                        @Override
                        public void onException(Throwable e) {
                            System.out.printf("%-10d Exception %s %n", index, e);
                            e.printStackTrace();
                        }
                    });
            }
            //Shut down once the producer instance is not longer in use.
            producer.shutdown();
        }
    }
    
    

    2.3以单向模式发送消息

    单向传输用于需要中等可靠性的情况,例如日志收集。

    public class OnewayProducer {
        public static void main(String[] args) throws Exception{
            //Instantiate with a producer group name.
            DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
            // Specify name server addresses.
            producer.setNamesrvAddr("192.168.247.132:9876");
            //Launch the instance.
            producer.start();
            for (int i = 0; i < 100; i++) {
                //Create a message instance, specifying topic, tag and message body.
                Message msg = new Message("TopicTest" /* Topic */,
                    "TagA" /* Tag */,
                    ("Hello RocketMQ " +
                        i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                );
                //Call send message to deliver message to one of brokers.
                producer.sendOneway(msg);
    
            }
            //Shut down once the producer instance is not longer in use.
            producer.shutdown();
        }
    }
    
    

    3.消费消息

    public class Consumer {
    
        public static void main(String[] args) throws InterruptedException, MQClientException {
    
            // Instantiate with specified consumer group name.
            DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name");
    
            // Specify name server addresses.
            consumer.setNamesrvAddr("192.168.247.132:9876");
    
            // Subscribe one more more topics to consume.
            consumer.subscribe("TopicTest", "*");
            // Register callback to execute on arrival of messages fetched from brokers.
            consumer.registerMessageListener(new MessageListenerConcurrently() {
    
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                    ConsumeConcurrentlyContext context) {
                    System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
    
            //Launch the consumer instance.
            consumer.start();
    
            System.out.printf("Consumer Started.%n");
        }
    }
    

    相关文章

      网友评论

        本文标题:三、RocketMQ快速开始

        本文链接:https://www.haomeiwen.com/subject/nddjbqtx.html