• Introduction

    RabbitMQ is a message broker. The principal idea is pretty simple: it accepts and forwards messages.

    RabbitMQ, and messaging in general, uses some jargon.

    • Producing means nothing more than sending. A program that sends messages is a producer. We'll draw it like that, with "P":

    • A queue is the name for a mailbox. It lives inside RabbitMQ. Although messages flow through RabbitMQ and your applications, they can be stored only inside a queue. A queue is not bound by any limits, it can store as many messages as you like ‒ it's essentially an infinite buffer. Many producers can send messages that go to one queue, many consumers can try to receive data from one queue. A queue will be drawn as like that, with its name above it:

    • Consuming has a similar meaning to receiving. A consumer is a program that mostly waits to receive messages. On our drawings it's shown with "C":

    Note that the producer, consumer, and broker do not have to reside on the same machine; indeed in most applications they don't.

    Hello World!

    (using the pika 0.9.8 Python client)

    Our "Hello world" won't be too complex ‒ let's send a message, receive it and print it on the screen. To do so we need two programs: one that sends a message and one that receives and prints it.

    Our overall design will look like:

    Producer sends messages to the "hello" queue. The consumer receives messages from that queue.

  • Sending

    Our first program send.py will send a single message to the queue. The first thing we need to do is to establish a connection with RabbitMQ server.

     #!/usr/bin/env python
    import pika connection = pika.BlockingConnection(pika.ConnectionParameters(
    'localhost'))
    channel = connection.channel()

    We're connected now, to a broker on the local machine - hence the localhost. If we wanted to connect to a broker on a different machine we'd simply specify its name or IP address here.

    Next, before sending we need to make sure the recipient queue exists. If we send a message to non-existing location, RabbitMQ will just trash the message. Let's create a queue to which the message will be delivered, let's name it hello:

     channel.queue_declare(queue='hello')

    At that point we're ready to send a message. Our first message will just contain a string Hello World! and we want to send it to our hello queue.

    In RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange. But let's not get dragged down by the details ‒ you can read more aboutexchanges in the third part of this tutorial. All we need to know now is how to use a default exchange identified by an empty string. This exchange is special ‒ it allows us to specify exactly to which queue the message should go. The queue name needs to be specified in the routing_key parameter:

     channel.basic_publish(exchange='',
    routing_key='hello',
    body='Hello World!')
    print " [x] Sent 'Hello World!'"

    Before exiting the program we need to make sure the network buffers were flushed and our message was actually delivered to RabbitMQ. We can do it by gently closing the connection.

     connection.close()
    
    

    Receiving

    Our second program receive.py will receive messages from the queue and print them on the screen.

    Again, first we need to connect to RabbitMQ server. The code responsible for connecting to Rabbit is the same as previously.

    The next step, just like before, is to make sure that the queue exists. Creating a queue using queue_declare is idempotent ‒ we can run the command as many times as we like, and only one will be created.

     channel.queue_declare(queue='hello')

    Receiving messages from the queue is more complex. It works by subscribing a callback function to a queue. Whenever we receive a message, this callback function is called by the Pika library. In our case this function will print on the screen the contents of the message.

     def callback(ch, method, properties, body):
    print " [x] Received %r" % (body,)

    Next, we need to tell RabbitMQ that this particular callback function should receive messages from our hello queue:

     channel.basic_consume(callback,
    queue='hello',
    no_ack=True)

    For that command to succeed we must be sure that a queue which we want to subscribe to exists. Fortunately we're confident about that ‒ we've created a queue above ‒ usingqueue_declare.

    The no_ack parameter will be described later on.And finally, we enter a never-ending loop that waits for data and runs callbacks whenever necessary.

  •  print ' [*] Waiting for messages. To exit press CTRL+C'
    channel.start_consuming()

    Putting it all together

    Full code for send.py:

     #!/usr/bin/env python
    import pika connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
    channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='',
    routing_key='hello',
    body='Hello World!')
    print " [x] Sent 'Hello World!'"
    connection.close()

    (send.py source)

    Full receive.py code:

     #!/usr/bin/env python
    import pika connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
    channel = connection.channel() channel.queue_declare(queue='hello') print ' [*] Waiting for messages. To exit press CTRL+C' def callback(ch, method, properties, body):
    print " [x] Received %r" % (body,) channel.basic_consume(callback,
    queue='hello',
    no_ack=True) channel.start_consuming()

    (receive.py source)

rabbitmq使用方法(一)的更多相关文章

  1. 最简单的 RabbitMQ 监控方法 - 每天5分钟玩转 OpenStack(158)

    这是 OpenStack 实施经验分享系列的第 8 篇. 先来看张图:这是 Nova 的架构图,我们可以看到有两个组件处于架构的中心位置:数据库和Queue.数据库保存状态信息,而几乎所有的 nova ...

  2. Rabbitmq各方法的作用详解

    exchange_declare('direct_logs', 'direct', false, false, false);// 这个是申明交换器,如果没有申明就给默认队列的这个交换器,而且发送的类 ...

  3. 一个非常简单用.NET操作RabbitMQ的方法

    RabbitMQ作为一款主流的消息队列工具早已广受欢迎.相比于其它的MQ工具,RabbitMQ支持的语言更多.功能更完善. 本文提供一种市面上最/极简单的使用RabbitMQ的方式(支持.NET/.N ...

  4. 登录RabbitMQ的方法

    一:(运行RabbitMQ之前需要先打开docker 容器)打开相应的路径,在windows Powershell 管理员下打开 输入:docker-compose -f .\docker-compo ...

  5. rabbitmq使用方法(二)

    Work Queues In the first tutorial we wrote programs to send and receive messages from a named queue. ...

  6. RabbitMQ高可用集群配置

    1.安装RabbitMQ 1)下载和安装erlang 下载erlang wget http://www.rabbitmq.com/releases/erlang/erlang-18.1-1.el6.x ...

  7. Python并发编程-RabbitMQ消息队列

    RabbitMQ队列 RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议. MQ全称为Message Queue, 消息队列 ...

  8. RabbitMQ学习(二):Java使用RabbitMQ要点知识

    转  https://blog.csdn.net/leixiaotao_java/article/details/78924863 1.maven依赖 <dependency> <g ...

  9. kubernetes安装rabbitmq集群

    1.准备K8S环境 2.下载基础镜像,需要安装两种插件:autocluster.rabbitmq_management 方法一: 下载已有插件镜像 [root@localhost ~]#docker ...

随机推荐

  1. 说说流控制(RTS/CTS/DTR/DSR 你都明白了吗?)【转】

    转自:http://bbs.ednchina.com/BLOG_ARTICLE_129041.HTM 以前写的博文,转过来 ============== 先引用一篇网文,作者不详,因几个地方都说自己是 ...

  2. c语言的重构、清理与代码分析图形化浏览工具: CScout

    网址: https://www.spinellis.gr/cscout/ https://www2.dmst.aueb.gr/dds/cscout/index.html https://github. ...

  3. Tengine HTTPS原理解析、实践与调试【转】

    本文邀请阿里云CDN HTTPS技术专家金九,分享Tengine的一些HTTPS实践经验.内容主要有四个方面:HTTPS趋势.HTTPS基础.HTTPS实践.HTTPS调试. 一.HTTPS趋势 这一 ...

  4. System.Runtime.InteropServices.COMException (0x800A03EC): 无法访问文件

    使用Microsoft.Office.Interop.Excel 操作 今天在服务器部署,操作程序csv文件转xsl文件的时候,遇到一下问题: System.Runtime.InteropServic ...

  5. saltStack的event接口通过mysql数据库接收SaltStack批量管理日志

    event是一个本地的ZeroMQ PUB Interface,event是一个开放的系统,用于发送信息通知salt或其他的操作系统.每个event都有一个标签.事件标签允许快速制定过滤事件.除了标签 ...

  6. 最新 macOS Sierra 10.12.3 安装CocoaPods及使用详解

    一.什么是CocoaPods 每种语言发展到一个阶段,就会出现相应的依赖管理工具,例如 Java 语言的 Maven,nodejs 的 npm.随着 iOS 开发者的增多,业界也出现了为 iOS 程序 ...

  7. Linux安全配置步骤简述

    一.磁盘分区  1.如果是新安装系统,对磁盘分区应考虑安全性:   1)根目录(/).用户目录(/home).临时目录(/tmp)和/var目录应分开到不同的磁盘分区:   2)以上各目录所在分区的磁 ...

  8. robotium之不标准select控件

    今天写脚本,遇到一个联合查询框 即:下拉框选择,输入框输入搜索条件,点击查询按钮 如图样式: 用uiautomatorviewer查看元素:无ID,无name,无desc 看到这我瞬间尴尬了,该咋办呢 ...

  9. 判断Javascript变量是否为空 undefined 或者null(附样例)

    1.变量申明未赋值 var type; //type 变量未赋值 1. type==undefined //true 2. type===undefined //true 3. typeof(type ...

  10. .net core定时任务

    1.HangFire HangFire官网 Hangfire项目实践分享 :  讲解的比较详细 2.Quartz.NET https://www.cnblogs.com/best/p/7658573. ...