rocketMq 安装和使用

一:rocketMq安装

1.官网下载:https://www.apache.org/

(需要jdk8以上环境先安装好)

rocketMq 安装和使用_第1张图片

2.解压,调整工作内存大小

# 解压
unzip rocketmq-all-4.5.2-bin-release.zip
# 修改目录名称
mv rocketmq-all-4.5.2-bin-release rocketmq
# 调整工作内容大小
# 调整启动内存为256m或128m
vim runserver.sh
vim runbroker.sh

3,更改配置文件,并开放许服务端口

brokerClusterName = DefaultCluster
brokerName = broker-a
brokerId = 0
deleteWhen = 04
fileReservedTime = 48
brokerRole = ASYNC_MASTER
flushDiskType = ASYNC_FLUS
# 解决和docker 冲突的
brokerIP1=外网服务器ip
namesrvAddr=外网服务器ip:9876

4,启动

#启动nameserv
sh mqnamesrv
#nameserv默认端口:9876

#在虚拟机中后台启动
nohup sh mqnamesrv &

# 启动mq  服务  -n 指定 nameserv 的地址(bin)
sh mqbroker -n localhost:9876  -c ../conf/broker.conf
#broker默认端口:10911

#在虚拟机中后台启动
nohup sh mqbroker -n localhost:9876  -c ../conf/broker.conf &
# windows 手动创建主题
mqadmin.cmd updateTopic -n 127.0.0.1:9876 -b 127.0.0.1:10911 -t Topic1
# 设置自动创建主题
mqbroker.cmd -n localhost:9876 autoCreateTopicEnable=true

5.测试

export NAMESRV_ADDR=localhost:9876
#执行测试
sh tools.sh org.apache.rocketmq.example.quickstart.Producer
sh tools.sh org.apache.rocketmq.example.quickstart.Consumer

二:搭建项目进行测试

1.pom依赖

>
     >org.apache.rocketmq>
     >rocketmq-client>
     >4.5.2>
>

2.消息生产

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 java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Provider {
    public static void main(String[] args) throws Exception {
//        test2();
//        test();
        test3();
    }
    // 事务消息
    private static void test3() throws MQBrokerException, RemotingException, InterruptedException, MQClientException, UnsupportedEncodingException {
        //事务消息使用的生产者是TransactionMQProducer
        TransactionMQProducer producer = new TransactionMQProducer("group1");
        producer.setNamesrvAddr("ip:port");
        //添加本地事务对应的监听
        producer.setTransactionListener(new TransactionListener() {
            //正常事务过程
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {

                // 此处写本地事务处理业务
                // 如果成功,消息改为提交,如果失败改为 回滚,如果是多线程处理状态未知,就提交为未知等待事务补偿过程

                //事务提交状态
                return LocalTransactionState.COMMIT_MESSAGE;// 类似于msql 的 commit
            }
            //事务补偿过程
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                return null;
            }
        });
        producer.start();

        Message msg = new Message("topic1",("事务消息:hello rocketmq ").getBytes("UTF-8"));
        SendResult result = producer.sendMessageInTransaction(msg,null);
        System.out.println("返回结果:"+result);
    }
    // 实时消息
    private static void test2() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        DefaultMQProducer producer=new DefaultMQProducer("group1");
        producer.setNamesrvAddr("ip:port");
        producer.start();

        Message msg=new Message("topic1","hello rocketMq!".getBytes(StandardCharsets.UTF_8));
        SendResult result=producer.send(msg);
        System.out.println(result);
        producer.shutdown();
    }
    // 顺序消息,发送者同意组消息发送到同一队列,接收者同一线程监听同一队列
    private static void test() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        DefaultMQProducer producer=new DefaultMQProducer("group1");
        producer.setNamesrvAddr("ip:port");
        producer.start();

        //创建要执行的业务队列
        List<Order> orderList = new ArrayList<Order>();

        Order order11 = new Order();
        order11.setId("a");
        order11.setMsg("主单-1");
        orderList.add(order11);

        Order order12 = new Order();
        order12.setId("a");
        order12.setMsg("子单-2");
        orderList.add(order12);

        Order order13 = new Order();
        order13.setId("a");
        order13.setMsg("支付-3");
        orderList.add(order13);

        Order order14 = new Order();
        order14.setId("a");
        order14.setMsg("推送-4");
        orderList.add(order14);

        Order order21 = new Order();
        order21.setId("b");
        order21.setMsg("主单-1");
        orderList.add(order21);

        Order order22 = new Order();
        order22.setId("b");
        order22.setMsg("子单-2");
        orderList.add(order22);

        Order order31 = new Order();
        order31.setId("c");
        order31.setMsg("主单-1");
        orderList.add(order31);

        Order order32 = new Order();
        order32.setId("c");
        order32.setMsg("子单-2");
        orderList.add(order32);

        Order order33 = new Order();
        order33.setId("c");
        order33.setMsg("支付-3");
        orderList.add(order33);

        for (Order order : orderList) {
            Message msg=new Message("topic1",order.toString().getBytes(StandardCharsets.UTF_8));
            SendResult result=producer.send(msg, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    int mqIndex = order.getId().hashCode() % list.size();
                    return list.get(mqIndex);
                }
            },null);
            System.out.println(result);
        }
        producer.shutdown();
    }

}

3,消息消费者

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

import java.util.List;

public class Consumer {
    public static void main(String[] args) throws MQClientException {
        // 普通消息
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        consumer.setNamesrvAddr("ip:port");
        consumer.subscribe("topic3", "*");

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list,
                                                            ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg : list) {
                    System.out.println("消息:" + new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
        System.out.println("接收消息服务已开启运行");
    }

    // 顺序消息消费
    private static void test() throws MQClientException {
        DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("group1");
        consumer.setNamesrvAddr("ip:port");
        consumer.subscribe("topic1","*");
        consumer.registerMessageListener(new MessageListenerOrderly() {

            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                for (MessageExt messageExt : list) {
                    System.out.println(Thread.currentThread().getName()+"消息:"+new String(messageExt.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        consumer.start();
        System.out.println("接受消息服务已开启。。。。。。");
    }
}

你可能感兴趣的:(java-rocketmq,rocketmq,java)