1. 程式人生 > >rocketmq-簡單入門例子

rocketmq-簡單入門例子

1、環境搭建快速開始
本章節主要詳細介紹如何在本地計算機上設定RocketMQ訊息系統以傳送和接收訊息.
在本章節

前置條件
下載發行版本並構建
啟動NAME SERVER服務
啟動BROKE服務
傳送並接收訊息
關閉服務
前置條件
假定安裝了以下軟體:

推薦64bit OS, Linux/Unix/Mac系統;
64bit JDK 1.8+;
Maven 3.2.x
Git
從釋出版下載並構建
點選 這裡 下載4.2.0發行版原始碼. 你也可以點選 這裡下載二進位制發行版.
直接看官網很簡單,雖然是英文,下載一個百度網頁翻譯就可以了
現在執行以下命令來解壓4.2.0源版本並構建.

unzip rocketmq-all-4.2.0-source-release.zip
cd rocketmq-all-4.2.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 &
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the “License”); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

1、傳送訊息
package com.ju.biz.mq.rokectmq.quickstart;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
* This class demonstrates how to send messages to brokers using provided {@link DefaultMQProducer}.
*/
public class Producer {
public static void main(String[] args) throws MQClientException, InterruptedException {

    /*
     * Instantiate with a producer group name.
     */
    DefaultMQProducer producer = new DefaultMQProducer("producer1");

    /*
     * Specify name server addresses.
     * <p/>
     *
     * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR
     * <pre>
     * {@code
     * producer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876");
     * }
     * </pre>
     */
    producer.setNamesrvAddr("192.168.0.103:9876");
    /*
     * Launch the instance.
     */
    producer.start();

    for (int i = 0; i < 1000; i++) {
        try {

            /*
             * 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);
        } catch (Exception e) {
            e.printStackTrace();
            Thread.sleep(1000);
        }
    }

    /*
     * Shut down once the producer instance is not longer in use.
     */
    producer.shutdown();
}

}
2、消費訊息
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the “License”); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ju.biz.mq.rokectmq.quickstart;

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.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
* This example shows how to subscribe and consume messages using providing {@link DefaultMQPushConsumer}.
*/
public class Consumer {

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

    /*
     * Instantiate with specified consumer group name.
     */
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer1");

    /*
     * Specify name server addresses.
     * <p/>
     *
     * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR
     * <pre>
     * {@code
     * consumer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876");
     * }
     * </pre>
     */
    consumer.setNamesrvAddr("192.168.0.103:9876");
    /*
     * Specify where to start in case the specified consumer group is a brand new one.
     */
    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

    /*
     * 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");
}

}