RabbitMQ 入门指南(Java)

返回原文英文原文:Getting Started with RabbitMQ in Java

RabbitMQ is a popular message broker typically used for building integration between applications or different components of the same application using messages. This post is a very basic introduction on how to get started using RabbitMQ and assumes you already have setup the rabbitmq server.

RabbitMQ is written in Erlang and has drivers/clients available for most major languages. We are using Java for this post therefore we will first get hold of the java client. The maven dependency for the java client is given below.

<dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><version>3.0.4</version>
</dependency>
译者信息

译者信息

LinuxQueen
翻译于 2年前

1人 顶 此译文

RabbitMQ是一个受欢迎的消息代理,通常用于应用程序之间或者程序的不同组件之间通过消息来进行集成。本文简单介绍了如何使用 RabbitMQ,假定你已经配置好了rabbitmq服务器。

RabbitMQ是用Erlang,对于主要的编程语言都有驱动或者客户端。我们这里要用的是Java,所以先要获得Java客户端。。下面是Java客户端的maven依赖的配置。

<dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><version>3.0.4</version>
</dependency>
While message brokers such as RabbitMQ can be used to model a variety of schemes such as one to one message delivery or publisher/subscriber, our application will  be simple enough and have two basic components, a single producer, that will produce a message and a single consumer that will consume that message.

In our example, the producer will produce a large number of messages, each message carrying a sequence number while the consumer will consume the messages in a separate thread.

译者信息

译者信息

LinuxQueen
翻译于 2年前

0人 顶 此译文

其它翻译版本:1(点击译者名切换)
Andy

像RabbitMQ这样的消息代理可用来模拟不同的场景,例如点对点的消息分发或者订阅/推送。我们的程序足够简单,有两个基本的组件,一个生产者用于产生消息,还有一个消费者用来使用产生的消息。

在这个例子里,生产者会产生大量的消息,每个消息带有一个序列号,另一个线程中的消费者会使用这些消息。

译者信息

译者信息

Andy
翻译于 2年前

0人 顶 此译文

其它翻译版本:1(点击译者名切换)
LinuxQueen

RabbitMQ之类的消息中间件可以有很多应用模式,例如点对点的消息传送,发布者-订阅者模式等等。我们的程序非常简单,就是两个模块,一个是生产者,产生消息,一个是订阅者,消费消息。

在下面的程序中,生产者将产生大量的消息,每个消息有一个序列号,消费者将有一个单独的线程读取这些消息。

The EndPoint Abstract class:

Let’s first write a class that generalizes both producers and consumers as ‘endpoints’ of a queue. Whether you are a producer or a consumer, the code to connect to a queue remains the same therefore we can generalize it in this class.

package co.syntx.examples.rabbitmq;import java.io.IOException;import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;/*** Represents a connection with a queue* @author syntx**/
public abstract class EndPoint{protected Channel channel;protected Connection connection;protected String endPointName;public EndPoint(String endpointName) throws IOException{this.endPointName = endpointName;//Create a connection factoryConnectionFactory factory = new ConnectionFactory();//hostname of your rabbitmq serverfactory.setHost("localhost");//getting a connectionconnection = factory.newConnection();//creating a channelchannel = connection.createChannel();//declaring a queue for this channel. If queue does not exist,//it will be created on the server.channel.queueDeclare(endpointName, false, false, false, null);}/*** Close channel and connection. Not necessary as it happens implicitly any way. * @throws IOException*/public void close() throws IOException{this.channel.close();this.connection.close();}
}
译者信息

译者信息

LinuxQueen
翻译于 2年前

1人 顶 此译文

抽象类EndPoint:

我们首先写一个类,将产生产者和消费者统一为 EndPoint类型的队列。不管是生产者还是消费者, 连接队列的代码都是一样的,这样可以通用一些。

package co.syntx.examples.rabbitmq;import java.io.IOException;import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;/*** Represents a connection with a queue* @author syntx**/
public abstract class EndPoint{protected Channel channel;protected Connection connection;protected String endPointName;public EndPoint(String endpointName) throws IOException{this.endPointName = endpointName;//Create a connection factoryConnectionFactory factory = new ConnectionFactory();//hostname of your rabbitmq serverfactory.setHost("localhost");//getting a connectionconnection = factory.newConnection();//creating a channelchannel = connection.createChannel();//declaring a queue for this channel. If queue does not exist,//it will be created on the server.channel.queueDeclare(endpointName, false, false, false, null);}/*** 关闭channel和connection。并非必须,因为隐含是自动调用的。 * @throws IOException*/public void close() throws IOException{this.channel.close();this.connection.close();}
}

The Producer:

The producer class is what is responsible for writing a message onto a queue. We are using Apache Commons Lang to convert a Serializable java object to a byte array. The maven dependency for commons lang is

<dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version>
</dependency>
package co.syntx.examples.rabbitmq;import java.io.IOException;
import java.io.Serializable;import org.apache.commons.lang.SerializationUtils;/*** The producer endpoint that writes to the queue.* @author syntx**/
public class Producer extends EndPoint{public Producer(String endPointName) throws IOException{super(endPointName);}public void sendMessage(Serializable object) throws IOException {channel.basicPublish("",endPointName, null, SerializationUtils.serialize(object));}
}
译者信息

译者信息

LinuxQueen
翻译于 2年前

0人 顶 此译文

生产者:

生产者类的任务是向队列里写一条消息。我们使用Apache Commons Lang把可序列化的Java对象转换成 byte 数组。commons lang的maven依赖如下:

<dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version>
</dependency>
package co.syntx.examples.rabbitmq;import java.io.IOException;
import java.io.Serializable;import org.apache.commons.lang.SerializationUtils;/*** The producer endpoint that writes to the queue.* @author syntx**/
public class Producer extends EndPoint{public Producer(String endPointName) throws IOException{super(endPointName);}public void sendMessage(Serializable object) throws IOException {channel.basicPublish("",endPointName, null, SerializationUtils.serialize(object));}
}

The Consumer:

The consumer, which can be run as a thread, has callback functions for various events, most important of which is the availability of a new message.

package co.syntx.examples.rabbitmq;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;import org.apache.commons.lang.SerializationUtils;import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;/*** The endpoint that consumes messages off of the queue. Happens to be runnable.* @author syntx**/
public class QueueConsumer extends EndPoint implements Runnable, Consumer{public QueueConsumer(String endPointName) throws IOException{super(endPointName);     }public void run() {try {//start consuming messages. Auto acknowledge messages.channel.basicConsume(endPointName, true,this);} catch (IOException e) {e.printStackTrace();}}/*** Called when consumer is registered.*/public void handleConsumeOk(String consumerTag) {System.out.println("Consumer "+consumerTag +" registered");        }/*** Called when new message is available.*/public void handleDelivery(String consumerTag, Envelope env,BasicProperties props, byte[] body) throws IOException {Map map = (HashMap)SerializationUtils.deserialize(body);System.out.println("Message Number "+ map.get("message number") + " received.");}public void handleCancel(String consumerTag) {}public void handleCancelOk(String consumerTag) {}public void handleRecoverOk(String consumerTag) {}public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {}
}
译者信息

译者信息

LinuxQueen
翻译于 2年前

1人 顶 此译文

消费者:

消费者可以以线程方式运行,对于不同的事件有不同的回调函数,其中最主要的是处理新消息到来的事件。

package co.syntx.examples.rabbitmq;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;import org.apache.commons.lang.SerializationUtils;import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;/*** 读取队列的程序端,实现了Runnable接口。* @author syntx**/
public class QueueConsumer extends EndPoint implements Runnable, Consumer{public QueueConsumer(String endPointName) throws IOException{super(endPointName);     }public void run() {try {//start consuming messages. Auto acknowledge messages.channel.basicConsume(endPointName, true,this);} catch (IOException e) {e.printStackTrace();}}/*** Called when consumer is registered.*/public void handleConsumeOk(String consumerTag) {System.out.println("Consumer "+consumerTag +" registered");        }/*** Called when new message is available.*/public void handleDelivery(String consumerTag, Envelope env,BasicProperties props, byte[] body) throws IOException {Map map = (HashMap)SerializationUtils.deserialize(body);System.out.println("Message Number "+ map.get("message number") + " received.");}public void handleCancel(String consumerTag) {}public void handleCancelOk(String consumerTag) {}public void handleRecoverOk(String consumerTag) {}public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {}
}

Putting it together:

In our driver class, we start a consumer thread and then proceed to generate a large number of messages that will be consumed by the consumer.

package co.syntx.examples.rabbitmq;import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;public class Main {public Main() throws Exception{QueueConsumer consumer = new QueueConsumer("queue");Thread consumerThread = new Thread(consumer);consumerThread.start();Producer producer = new Producer("queue");for (int i = 0; i < 100000; i++) {HashMap message = new HashMap();message.put("message number", i);producer.sendMessage(message);System.out.println("Message Number "+ i +" sent.");}}/*** @param args* @throws SQLException * @throws IOException */public static void main(String[] args) throws Exception{new Main();}
}
译者信息

译者信息

LinuxQueen
翻译于 2年前

1人 顶 此译文

Putting it together:

在下面的测试类中,先运行一个消费者线程,然后开始产生大量的消息,这些消息会被消费者取走。

package co.syntx.examples.rabbitmq;import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;public class Main {public Main() throws Exception{QueueConsumer consumer = new QueueConsumer("queue");Thread consumerThread = new Thread(consumer);consumerThread.start();Producer producer = new Producer("queue");for (int i = 0; i < 100000; i++) {HashMap message = new HashMap();message.put("message number", i);producer.sendMessage(message);System.out.println("Message Number "+ i +" sent.");}}/*** @param args* @throws SQLException * @throws IOException */public static void main(String[] args) throws Exception{new Main();}
}

RabbitMQ入门指南二(Java)相关推荐

  1. RabbitMQ入门(二)-helloworld

    首先引入pom依赖: <dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-clien ...

  2. RabbitMQ入门指南:初学者也能读懂的教程

    文章目录 1.消息队列 1.1.MQ的相关概念 1.1.1.什么是MQ 1.1.2.为什么要使用MQ 流量削峰 应用解耦 异步处理 1.1.3.MQ的分类 ActiveMQ KafKa RocketM ...

  3. Adobe Achemy入门指南(二)

    在第一篇入门文章介绍了Achemy的基本知识,本文将介绍了了一个新的知识点,即如何从c代码中调用外部的actionscript3代码. 这在实际中有许多地方可以应用到. 思路很简单:就是常用的回调的概 ...

  4. Elasticsearch 快速入门指南(二)

    东风夜放花千树.更吹落星如雨. 5.Spring Data Elasticsearch Elasticsearch提供的Java客户端有一些不太方便的地方: 很多地方需要拼接Json字符串,在java ...

  5. 微信小程序开发入门指南二

    上篇文章我们已经一起成功创建了一个Hello World级别的微信小程序. 那么这篇文章我们将详细讲解下这个例子中的相关代码部分. 代码构成 正如你所看到的,这个项目中生成了很多不同类型的文件. .j ...

  6. 编程入门指南 v1.4

    著作权归作者所有. 商业转载请联系作者获得授权,非商业转载请注明出处. 作者:Badger 链接:http://zhuanlan.zhihu.com/xiao-jing-mo/19959253 来源: ...

  7. RabbitMQ入门到进阶

    1.MQ简介 MQ 全称为 Message Queue,是在消息的传输过程中保存消息的容器.多用于分布式系统 之间进行通信. 2.为什么要用 MQ 1.流量消峰 没使用MQ 使用了MQ 2.应用解耦 ...

  8. RabbitMQ入门到进阶(Spring整合RabbitMQSpringBoot整合RabbitMQ)

    1.MQ简介 MQ 全称为 Message Queue,是在消息的传输过程中保存消息的容器.多用于分布式系统 之间进行通信. ​ 编辑切换为居中 添加图片注释,不超过 140 字(可选) 2.为什么要 ...

  9. 《转载》编程入门指南 v1.4

    编程入门指南 v1.4 Badger · 8 个月前 作者:@萧井陌, @Badger 自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0 CoCode ...

  10. 【K8S系列】深入解析 k8s:入门指南(一)

    目录 序言 1.背景介绍 2.前情提要 2.1 架构对比 2.2 容器技术 2.3 容器技术的优点 2.4 容器编排 3 K8S介绍 3.1 K8S是什么 3.2 K8S设计思想 3.3 K8S的优势 ...

最新文章

  1. oracle19c数据库清理,Oracle 19c集群重装
  2. VisualStudioCode 中设置中文语言【图文教程】
  3. CVPR 2019 | 针对人脸识别系统的高效黑盒对抗攻击算法
  4. idea(一)使用详解
  5. Python中的支持向量机SVM的使用(有实例有源码)
  6. [ warning] [vmusr:vmtoolsd] Failed registration of app type 2 (Signals)
  7. Code First :使用Entity. Framework编程(7) ----转发 收藏
  8. ajax表格内容加按钮,单击按钮时,如何触发jquery数据表fnServerData通过AJAX更新表?...
  9. arcgis创建剖面线execl文件
  10. 信息学奥赛一本通 1164:digit函数
  11. 【记录贴】cs231n课程作业一遇到问题总结
  12. 用android编写使用按钮ImageButton和切换器ImageSwitcher
  13. iOS设置启动页并适配机型
  14. 港科夜闻|沈向洋教授获委任为香港科大校董会主席
  15. Every Document Owns Its Structure: Inductive Text Classification via GNN (TextING)
  16. 随机验证码生成(生成一个含有n位随机数字的字符串)
  17. 浅谈集合List,Set以及Map集合的特点及区别
  18. 【肌电信号】脉搏信号分析(去噪+特征提取)matlab源码含GUI
  19. 华为、阿里等知名公司年终奖发了多少?
  20. Prezi快捷键记忆

热门文章

  1. Spring 学习笔记---Bean的生命周期
  2. 查询检测PhysX 3.2中的场景查询(1)-基础
  3. cf 165 div2 解题报告
  4. vc++6.0如何调试
  5. linux系统进去dev sdb6,linux书上划的题的答案
  6. java文件读写 教程_Java对文件的读写操作(图文详解)
  7. 使用systemd管理程序进程
  8. 图形学初探(一)图形学基础和基本术语
  9. 美化下拉框select箭头部分(不彻底)
  10. Oracle执行计划 讲解(二) .