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

}

猜你喜欢

转载自blog.csdn.net/u014362882/article/details/80422424