RocketMQ是阿里巴巴在2012年开源的分布式消息中间件,目前已经捐赠给Apache基金会,已经于2016年11月成为 Apache 孵化项目,相信RocketMQ的未来会发挥着越来越大的作用,将有更多的开发者因此受益。

本文仅对RocketMQ的简单实用做入门性介绍,不对RocketMQ的底层原理进行深入介绍,后续文章将对RocketMQ的原理做详细介绍。

RocketMQ的Maven依赖:

<!-- https://mvnrepository.com/artifact/com.alibaba.rocketmq/rocketmq-client -->
<dependency>
<groupId>com.alibaba.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>3.2.6</version>
</dependency>

MQ的消费类RocketMQConsumer.java:

package com.lance.rocketMQ.RocketMQ;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.MessageListener;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere; import java.util.UUID; /**
* Created by lance on 2017/2/10.
*/
public class RocketMQConsumer { private DefaultMQPushConsumer consumer; private MessageListener listener; protected String nameServer; protected String groupName; protected String topics; public RocketMQConsumer(MessageListener listener, String nameServer, String groupName, String topics) {
this.listener = listener;
this.nameServer = nameServer;
this.groupName = groupName;
this.topics = topics;
} public void init() {
consumer = new DefaultMQPushConsumer(groupName);
consumer.setNamesrvAddr(nameServer);
try {
consumer.subscribe(topics, "*");
} catch (MQClientException e) {
e.printStackTrace();
}
consumer.setInstanceName(UUID.randomUUID().toString());
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
consumer.registerMessageListener((MessageListenerConcurrently) this.listener); try {
consumer.start();
} catch (MQClientException e) {
e.printStackTrace();
}
System.out.println("RocketMQConsumer Started! group=" + consumer.getConsumerGroup() + " instance=" + consumer.getInstanceName()
);
} }

MQ消息的监听接口类RocketMQListener.java

package com.lance.rocketMQ.RocketMQ;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.message.MessageExt; import java.util.List; /**
* Created by lance on 2017/2/10.
*/
public class RocketMQListener implements MessageListenerConcurrently { @Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
// System.out.println("get data from rocketMQ:" + msgs);
for (MessageExt message : msgs) { String msg = new String(message.getBody());
System.out.println("msg data from rocketMQ:" + msg);
} return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}

MQ消息的生产者类RocketMQProducer.java

package com.lance.rocketMQ.RocketMQ;

import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.client.producer.SendStatus;
import com.alibaba.rocketmq.common.message.Message; import java.util.UUID; /**
* Created by lance on 2017/2/10.
*/
public class RocketMQProducer { private DefaultMQProducer sender; protected String nameServer; protected String groupName; protected String topics; public void init() {
sender = new DefaultMQProducer(groupName);
sender.setNamesrvAddr(nameServer);
sender.setInstanceName(UUID.randomUUID().toString());
try {
sender.start();
} catch (MQClientException e) {
e.printStackTrace();
}
} public RocketMQProducer(String nameServer, String groupName, String topics) {
this.nameServer = nameServer;
this.groupName = groupName;
this.topics = topics;
} public void send(Message message) { message.setTopic(topics); try {
SendResult result = sender.send(message);
SendStatus status = result.getSendStatus();
System.out.println("messageId=" + result.getMsgId() + ", status=" + status);
} catch (Exception e) {
e.printStackTrace();
}
}
}

测试RocketMQ的消费 RocketMQConsumerTest.java

package com.lance.rocketMQ.RocketMQ;

/**
* Created by lance on 2017/2/10.
*/
public class RocketMQConsumerTest { public static void main(String[] args) { String mqNameServer = "172.10.254.2:9876";
String mqTopics = "MQ-MSG-TOPICS-TEST"; String consumerMqGroupName = "CONSUMER-MQ-GROUP";
RocketMQListener mqListener = new RocketMQListener();
RocketMQConsumer mqConsumer = new RocketMQConsumer(mqListener, mqNameServer, consumerMqGroupName, mqTopics);
mqConsumer.init(); try {
Thread.sleep(1000 * 60L);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}

测试RocketMQ的消费 RocketMQConsumerTest.java

package com.lance.rocketMQ.RocketMQ;

/**
* Created by lance on 2017/2/10.
*/
public class RocketMQConsumerTest { public static void main(String[] args) { String mqNameServer = "172.10.254.2:9876";
String mqTopics = "MQ-MSG-TOPICS-TEST"; String consumerMqGroupName = "CONSUMER-MQ-GROUP";
RocketMQListener mqListener = new RocketMQListener();
RocketMQConsumer mqConsumer = new RocketMQConsumer(mqListener, mqNameServer, consumerMqGroupName, mqTopics);
mqConsumer.init(); try {
Thread.sleep(1000 * 60L);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}

run RocketMQConsumerTest.java 之后,控制台输出:

RocketMQConsumer Started! group=CONSUMER-MQ-GROUP instance=1eb7d308-4414-4658-90b5-e2cae3b793eb

结果分析: 此时MQ对应的TOPIC中并没有响应的消息,故收不到消息,仅看到MQ消费者正常启动信息。

MQ的生产者测试类:RocketMQProducerTest.java

package com.lance.rocketMQ.RocketMQ;

import com.alibaba.rocketmq.common.message.Message;

/**
* Created by lance on 2017/2/10.
*/
public class RocketMQProducerTest { public static void main(String[] args) { String mqNameServer = "172.10.254.2:9876";
String mqTopics = "MQ-MSG-TOPICS-TEST"; String producerMqGroupName = "PRODUCER-MQ-GROUP";
RocketMQProducer mqProducer = new RocketMQProducer(mqNameServer, producerMqGroupName, mqTopics);
mqProducer.init(); for (int i = 0; i < 5; i++) { Message message = new Message();
message.setBody(("I send message to RocketMQ " + i).getBytes());
mqProducer.send(message);
} } }

run RocketMQProducerTest.java 之后,RocketMQProducerTest.java 对应的控制台输出为:

  1. messageId=0A71290100002A9F00000003D0BB0832, status=SEND_OK
  2. messageId=0A71290100002A9F00000003D0BB08BB, status=SEND_OK
  3. messageId=0A71290100002A9F00000003D0BB0944, status=SEND_OK
  4. messageId=0A71290100002A9F00000003D0BB09CD, status=SEND_OK
  5. messageId=0A71290300002A9F000000005440AEED, status=SEND_OK

结果分析:表明所有消息都已经正常发送,且被RocketMQ正常接收。

此时查看RocketMQConsumerTest.java对应的控制台输出发生改变,输出内容变更如下:

  1. RocketMQConsumer Started! group=CONSUMER-MQ-GROUP instance=1eb7d308-4414-4658-90b5-e2cae3b793eb
  2. msg data from rocketMQ:I send message to RocketMQ 1
  3. msg data from rocketMQ:I send message to RocketMQ 0
  4. msg data from rocketMQ:I send message to RocketMQ 3
  5. msg data from rocketMQ:I send message to RocketMQ 2
  6. msg data from rocketMQ:I send message to RocketMQ 4

看,简单吧!

备注:小编自己使用了Apache版本的RocketMQ(即RocketMQ 4.*),发现只需要更改import的package的路径而已,不需要修改其他代码,请参考。

RocketMQ的重复问题解决方式:
a.MQ的消费端执行的操作具有幂等性,即无论多少次重复执行,其结果是一样的;
b.MQ的消费端做重复校验,比如将受到MQ消息的唯一编号保存到Redis中,即每次收到消息时,将检查唯一编号是否已经在Redis中,如果存在说明消息重复;否则将唯一编号放入到Redis中,可以根据系统需要设置唯一编号在Redis中的过期时间,以防止Redis溢出。

Java操作RockeMQ的更多相关文章

  1. Java操作Sqlite数据库-jdbc连接

    Java操作Sqlite数据库步骤: 1. 导入Sqlite jdbc 本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD 2 ...

  2. 【MongoDB for Java】Java操作MongoDB

    上一篇文章: http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过 ...

  3. Java操作Oracle

    public class DBCon { // 数据库驱动对象 public static final String DRIVER = "oracle.jdbc.driver.OracleD ...

  4. JAVA操作ORACLE数据库的存储过程

    一.任务提出 JAVA操作oracle11g存储过程实验需要完成以下几个实例: 1.调用没有返回参数的过程(插入记录.更新记录) 2.有返回参数的过程 3.返回列表的过程 4.返回带分页的列表的过程. ...

  5. JAVA操作MongoDB数据库

    1. 首先,下载MongoDB对Java支持的驱动包 驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads 2.Java操作Mo ...

  6. Java操作Session与Cookie

    1,Java操作Session Java操作Session非常简单,步骤如下 1.1,在servlet中通过request获取session HttpSession session = request ...

  7. JAVA操作COOKIE

    JAVA操作COOKIE 1.设置Cookie Cookie cookie = new Cookie("key", "value"); cookie.setMa ...

  8. [转]MongoDB for Java】Java操作MongoDB

    原文地址: MongoDB for Java]Java操作MongoDB 开发环境: System:Windows IDE:eclipse.MyEclipse 8 Database:mongoDB 开 ...

  9. Java操作文件夹的工具类

    Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...

随机推荐

  1. [PHP插件教程]001.Pear包管理器

    PEAR是PHP扩展与应用库(the PHP Extension and Application Repository)的缩写.它是一个PHP扩展及应用的一个代码仓库. 简单地说,PEAR之于PHP就 ...

  2. PreparedStatement实现表数据的增删改 & 封装数据库链接和关闭操作

    PreparedStatement实现表数据的增删改 PreparedStatementUpdateTest package com.aff.PreparedStatement; import jav ...

  3. while与do-while循环的使用

    /* 1.格式: ①初始化条件 while(②循环条件){ ④循环体 ③迭代条件 } 2.for循环与while可以相互转换的 . */ public class TestWhile { //100以 ...

  4. GNS3配置问题(持续更新)

    GNS3配置问题 1.关于All in One的GNS3提示"判断dynamips版本失败"的解决办法 当我们找到GNS3根目录里的dynamips.exe,执行会报错告诉我们缺少 ...

  5. jQuery-显示与隐藏

    1.显示与隐藏 show([speed,easing,function]) speed:毫秒单位的时间值 hide([speed,easing,function]) 用法:元素.show()/元素.h ...

  6. oeong.xyz

    兴趣使然而搭的小破站:oeong.xyz

  7. layui插件croppers的使用

    这是我第一次在layui环境下面使用croppers插件.先粘贴下前端代码并附上我的目录结构吧.       @{   ViewData["Title"] = "Crop ...

  8. ActiveMQ 笔记(七)ActiveMQ的多节点集群

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.Activemq 的集群思想 1.使用Activemq集群的原因 面试题: 引入消息中间件后如何保证 ...

  9. Java实现洛谷 P1072 Hankson 的趣味题

    P1072 Hankson 的趣味题 输入输出样例 输入 2 41 1 96 288 95 1 37 1776 输出 6 2 PS: 通过辗转相除法的推导 import java.util.*; cl ...

  10. Java实现 LeetCode 131 分割回文串

    131. 分割回文串 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回 s 所有可能的分割方案. 示例: 输入: "aab" 输出: [ ["aa ...