欢迎来访我的博客。

消息队列之RabbitMQ-03_发布订阅

其他 小张哥哥 619浏览 42评论

前面文章中的工作队列,生产者生产的一个消息通过消息队列最终分发给一个消费者消费。
在本文中,我们来看以下一个不同形式的消息队列,即“发布/订阅”模式。
在这种模式下,一个生产者发出的一个消息,经过消息队列最终分发给多个消费者。

我们通过做一个简单的日志系统。日志系统包括两个程序。一个程序负责发送日志消息,另一个程序负责获取消息内容并输出。
在日志系统中,所有正在运行的接收程序都会接收消息,我们用其中过一个接收者把日志写入硬盘,另一个接收者把日志输出到屏幕上。


交换机
在前面的例子中,我们都把exchange赋值为空字符串,使用默认的。现在我们需要用到该交换机了。

RabbitMQ消息模型的核心理念是:发布者不会直接发送消息给队列,甚至都不知道消息是否已经被投递给队列。发布者只需要把消息发送给一个交换机(exchange)。交换机从发布者乙方接收消息,另一边把消息推送到队列。交换机知道如何处理它收到的消息,是推送到指定的队列还是多个队列,或者直接忽略该消息。交换机是通过其类型(exchange type)来定义的。

publisher_subscriber_exchange.png

交换机的类型有几种,直连交换机(direct),主题交换机(topic), 头交换机(heanders)和扇形交换机(fanout).

我们现在的发布订阅模式则需要使用fanout交换机。
我们现在定义一个fanout类型的交换机,名字命名为logs:

channel.exchange_declare(exchange='logs',
                         type='fanout')

扇形交换机就是把消息发送给它所知道的所有队列。

我们可以使用rabbitmqctl列出服务器上的所有交换器
$ sudo rabbitmqctl list_exchanges
logs fanout
amq.direct direct
amq.topic topic
amq.fanout fanout
amq.headers headers
...done.

匿名交换器
前面我们对交换机一无所知,但仍然能够发送消息到队列中。因为我们使用了命名为空字符串("")默认的交换机。
exchange参数就是交换机的名称。空字符串代表默认或者匿名交换机:消息将会根据指定的routing_key分发到指定的队列

现在我们就可以将消息发到一个带名字的交换机上了

channel.basic_publish(exchange='logs',
                      routing_key='',
                      body=message)

临时队列
前面的文章中,我们需要生产者和消费者共享队列,所以将队列名字命名为相同。
但是现在,对于我们的日志系统,我们打算接收所有的日志消息,而且,我们只关心最新的消息而不是旧的。在此,我们需要做以下两件事情。
首先,当我们连上RabbitMQ的时候,我们需要一个全新的,空的队列。我们可以手动创建一个随机的队列名,或者让服务器为我们选择一个随机的队列名。我们只需要在调用queue_declare方法的时候,不提供queue参数就可以了。

result = channel.queue_declare()

这种情况下,我们可以通过result.method.queue获取随机生成的队列名。

然后,当消费者断开连接的时候,这个队列应当被立即删除。exclusive标识符即可达到此目的。

result = channel.queue_declare(exclusive=True)

绑定
现在,我们已经创建了一个扇形交换机(fanout)和一个队列。现在我们需要告诉交换机如何发送消息给我们的队列。我们通过绑定交换机和队列来达到这个目的。

channel.queue_bind(exchange='logs',
                   queue=result.method.queue)

现在logs交换机就会把消息添加到我们的队列中了。

publisher_subscriber_binding.png

完整代码
publisher_subscriber.png

发布日志消息和之前的生产者没有太大区别。其中最重要的一点就是把消息发送给logs交换机而不是匿名交换机,在发送的时候我们需要提供routing_key参数,但是在扇形交换机情况下,该值会被忽略。
改写后的emit_log.py文件如下:

import sys
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
                         exchange_type='fanout')

message = ' '.join(sys.argv[1:]) or "Hello World!"

channel.basic_publish(exchange='logs',
                      routing_key='hello',
                      body=message)

print('[x] Sent %r' %message)
connection.close()

在上面代码中,在连接RabbitMQ成功之后,我们声明了一个交换机,然后将消息绑定到了交换机上。如果我们没有将交换机绑定,则此时没有消费者监听,消息会被忽略。

recieve_log.py

import time
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
                         exchange_type='fanout')

result = channel.queue_declare(exclusive=True)

channel.queue_bind(exchange='logs',
                   queue=result.method.queue)

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

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

channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_message_callback=callback,
                      queue=result.method.queue,
                      auto_ack=True)

channel.start_consuming()

如果我们需要把日志保存到文件中,我们可以在命令行中输入:

(learn_rabbitmq) $ python receive_logs.py > logs_from_rabbit.log

我们再打开一个新的终端,用于在屏幕中查看日志信息。

(learn_rabbitmq) $ python receive_logs.py

然后我们在另一个终端中发送日志信息。

(learn_rabbitmq) $ python emit_log.py


我们可以使用rabbitmqctl list_bindings来确认创建的队列已经被绑定。

$ sudo rabbitmqctl list_bindings
[sudo] password for zcw:
Listing bindings
......
exchange	0e8e00a732014c8d9193a1f324c6fc37	queue 0e8e00a732014c8d9193a1f324c6fc37	[]
exchange	3becf532429449fdaeb71ddcd0634c41	queue 3becf532429449fdaeb71ddcd0634c41	[]
exchange	5a3ae673963145f98d2383a5abde6d7b	queue 5a3ae673963145f98d2383a5abde6d7b	[]
......


转载请注明:禅思 » 消息队列之RabbitMQ-03_发布订阅?

喜欢 (1) or 分享 (0)

我的个人微信公众号,欢迎关注

扫码或搜索:Python后端开发Django

Python后端开发Django

微信公众号 扫一扫关注

结交朋友、一起学习,一起进步。

科波之主

QQ号 386046154 立即加入

添加微信,进行技术交流

专注技术交流, 一同成长进步

我的微信号

如果您喜欢我的文章,感觉我的文章对您有帮助,请狠狠点击下面

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(42)个小伙伴在吐槽
    1. 5ad031 cialis generico e legale https://tadaladilss.com/ preis fr viagra an walmart https://via1buynow.com/ kopen online viagra universal http://viagener2020.com/
      Toscofug 2020-10-27 21:34:18 回复
      • fb7411 cialis generico monterrey online cialiscialis generika online buy cialis online
        Leonillafug 2020-10-28 16:09:31 回复
        • reviews of is at 8b99 is store california 8b99 espeistas en dependencias 8b99
          Khloeefug 2020-11-01 23:04:38 回复
          • find my credit score https://webcreditscores.com/ - experian free credit score free credit report annual get credit report - free credit report
            arimbRoyarm 2020-12-16 11:10:33 回复
            • my credit score free https://creditscoresmy.com/ - discover credit score checking credit score transunion credit score free transunion credit report
              erarryinytemo 2020-12-21 16:38:20 回复
              • https://freecreditreportstats.com/ free credit transunion free credit score free credit score karma transunion credit report dispute
                unfodyendeagign 2020-12-21 23:32:39 回复
                • credit reporting agency https://freecreditreportstats.com/ myfreecreditreport what credit score for mortgage annual credit report completely free government
                  FressyArraday 2020-12-22 16:10:13 回复
                  • transunion free credit report https://creditreportcheckstats.com/ - turbotax credit report what is the highest credit score possible boost credit score
                    arimbRoyarm 2020-12-24 22:04:12 回复
                    • https://creditreportcheckstats.com/ highest credit score https://creditreportcheckstats.com/ - how to ck my credit score max credit score
                      PlableCesek 2020-12-25 13:36:35 回复
                      • https://creditreportcheckstats.com/ free credit credit score https://creditreportcheckstats.com/ - free yearly credit report karma free credit score
                        FressyArraday 2020-12-26 13:11:14 回复
                        • credit score scale view my credit report my free credit report annual
                          PlableCesek 2020-12-27 15:45:00 回复
                          • credit score online https://creditreportcheckstats.com/ - my free annual credit report check your credit report my annual credit report https://creditreportcheckstats.com/
                            erarryinytemo 2020-12-27 16:46:01 回复
                            • hemp oil for pain https://cbdoilforsalejmm.com/ - where to buy cbd oil what is cbd oil good for joy organics cbd cbd gummies for sale walmart
                              erarryinytemo 2020-12-29 20:31:11 回复
                              • mens ed pills canadian pharmacy online canada drugs online
                                Lokuamomi 2021-01-09 16:52:45 回复
                                • come dimagrire
                                  OscarWax 2021-01-12 22:15:23 回复
                                  • medicine for impotence ed drug prices
                                    MathewZer 2021-02-05 17:56:00 回复
                                    • https://casinorealmoneyiw.com/ casino bonus codes https://casinorealmoneyiw.com/ - online gambling casino game
                                      FressyArraday 2021-02-08 23:30:33 回复
                                      • Enjoy our scandal amateur galleries that looks incredibly dirty http://lipsticklesbian.pornautorank.instasexyblog.com/?morgan ffxii ashe porn xxx porn stars tube clips porn on htc pro los angeles porn industry french grandma porn videos
                                        gordonyt11 2021-02-11 06:46:01 回复
                                        • buy ciplox buy clindamycin generic order trimox online
                                          Carltonweafe 2021-02-12 12:19:02 回复
                                          • play online casino best online casinos online slot games
                                            elemVuretle 2021-02-16 00:48:19 回复
                                            • https://onlinecasinowps.com/ casino real money play casino free slots games slots online
                                              FressyArraday 2021-02-17 03:40:05 回复
                                              • online casino bonus big fish casino casino game
                                                elemVuretle 2021-02-17 07:34:16 回复
                                                • online casino real money free casino games online gambling no deposit casino https://onlinecasinosam.com/ - real money casino
                                                  DicSmeliCascisa 2021-02-17 08:35:25 回复
                                                  • slots games free https://playcasinoslotsmatic.com/ play slots online play slots casino online
                                                    FressyArraday 2021-02-17 08:56:04 回复
                                                    • Do you want to sound to the whole world? Want to publish your cover on all streaming platforms? License and publish your cover. Are you good at singing covers? It's time for the whole world to know about you! We will get all the permissions for you and post your cover version of the song on all leading digital platforms (iTunes, Apple Music, Amazon, Google Play, Yandex Music, YouTube Music, Spotify, Zvooq, Tidal, Deezer, TikTok and others). ). You only pay for licensing services. Distribution to digital platforms is free. You will receive 85% of the net profit from the sale of a cover version of the song every quarter. music distribution germany
                                                      Musicnep 2021-02-17 12:32:52 回复
                                                      • free casino games https://freecasinoslotsnow.com/ casino game free slots slot games
                                                        RapautorsAmoma 2021-02-17 13:35:00 回复
                                                        • https://freecasinogamesms.com/ online slots online casino games free casino games online casino game
                                                          RapautorsAmoma 2021-02-17 16:51:01 回复
                                                          • kamagra website reviews: https://www.kamagramama.com kamagra oral jelly healthcare,gov kamagra kamagra tabletten grГјn
                                                            www.kamagramama.com 2021-02-18 00:41:03 回复
                                                            • ничего особенного _________________ казино запрещено в украине, действующие казино на украине, взлом ігри на гроші.
                                                              KennethOvank 2021-02-21 11:33:32 回复
                                                              • חדרים לפי שעה חדרים לפי שעה
                                                                LarryPeefe 2021-02-25 00:10:04 回复
                                                                • legitimate cialis by mail cialis online interactions for cialis
                                                                  Buddyevera 2021-02-25 09:27:32 回复
                                                                  • difference between viagra and levitra cheap levitra online where can i buy levitra
                                                                    Labdamomi 2021-03-02 16:25:52 回复
                                                                    • tadalafil 40 mg daily generic tadalafil 40 mg tadalafil
                                                                      Wesleyviord 2021-03-05 12:40:30 回复
                                                                      • Engineering Engine-tips forum
                                                                        Coreyjonry 2021-03-05 19:55:04 回复
                                                                        • what is a credit score free credit karma my credit score
                                                                          unfodyendeagign 2021-03-05 20:12:49 回复
                                                                          • sildenafil over the counter usa buy sildenafil citrate online sildenafil 100mg price walmart
                                                                            KgooDrity 2021-03-06 01:03:11 回复
                                                                            • highest credit score https://creditscoresrw.com/ - credit reporting agency free credit score online annual credit score my annual credit report free
                                                                              elemVuretle 2021-03-06 01:13:29 回复
                                                                              • https://freecasinogameslab.com/ free slots slotomania https://freecasinogameslab.com/ - heart of vegas casino game free casino games slots
                                                                                unfodyendeagign 2021-03-06 01:23:51 回复
                                                                                • slots games https://freecasinogameslab.com/ - free slot games download full version casino slot machine games lady luck online casino
                                                                                  unfodyendeagign 2021-03-06 02:56:29 回复