最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python RabbitMQ實(shí)現(xiàn)簡(jiǎn)單的進(jìn)程間通信示例

 更新時(shí)間:2020年07月02日 11:05:14   作者:Xue__Feng  
這篇文章主要介紹了Python RabbitMQ實(shí)現(xiàn)簡(jiǎn)單的進(jìn)程間通信示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

RabbitMQ    消息隊(duì)列

PY
threading Queue
進(jìn)程Queue 父進(jìn)程與子進(jìn)程,或同一父進(jìn)程下的多個(gè)子進(jìn)程進(jìn)行交互
缺點(diǎn):兩個(gè)不同Python文件不能通過(guò)上面兩個(gè)Queue進(jìn)行交互

erlong
基于這個(gè)語(yǔ)言創(chuàng)建的一種中間商
win中需要先安裝erlong才能使用
rabbitmq_server start

安裝 Python module

pip install pika

or

easy_install pika

or
源碼

rabbit      默認(rèn)端口15672
查看當(dāng)前時(shí)刻的隊(duì)列數(shù)
rabbitmqctl.bat list_queue

exchange
在定義的時(shí)候就是有類型的,決定到底哪些queue符合條件,可以接受消息
fanout:所有bind到此exchange的queue都可以收到消息
direct:通過(guò)routingkey和exchange決定唯一的queue可以接受消息
topic: 所有符合routingkey(此時(shí)可以是一個(gè)表達(dá)式)的routingkey所bind的queue都可以接受消息
      表達(dá)式符號(hào)說(shuō)明:
      # 代表一個(gè)或多個(gè)字符     * 代表任何字符

RPC
remote procedure call           雙向傳輸,指令<-------->指令執(zhí)行結(jié)果
實(shí)現(xiàn)方法:                        創(chuàng)建兩個(gè)隊(duì)列,一個(gè)隊(duì)列收指令,一個(gè)隊(duì)列發(fā)送執(zhí)行結(jié)果

用rabbitmq實(shí)現(xiàn)簡(jiǎn)單的生產(chǎn)者消費(fèi)者模型

1) rabbit_producer.py

# Author : Xuefeng

import pika

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()

# create the queue, the name of queue is "hello"
# durable=True can make the queue be exist, although the service have stopped before.
channel.queue_declare(queue="hello", durable=True)

# n RabbitMQ a message can never be sent directly to queue,it always need to go through
channel.basic_publish(exchange = " ",
      routing_key = "hello",
      body = "Hello world!",
      properties = pika.BasicPropreties(
       delivery_mode=2, # make the message persistence
      )
      )
print("[x] sent 'Hello world!'")
connection.close()

2) rabbit_consumer.py

# Author : Xuefeng

import pika

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()
channel.queue_declare(queue="hello", durable=True)

def callback(ch, method, properties, body):
 '''
 Handle the recieved data
 :param ch: The address of the channel
 :param method: Information about the connection
 :param properties:
 :param body:
 :return:
 '''
 print("------>", ch, method, properties )
 print("[x] Recieved %r" % body)
 # ack by ourself
 ch.basic_ack(delivery_tag = method.delivery_tag)

# follow is for consumer to auto change with the ability
channel.basic_qos(profetch_count=1)
# no_ack = True represent that the message cannot be transfor to next consumer,
# when the current consumer is stop by accident.
channel.basic_consume(callback,  # If have recieved message, enable the callback() function to handle the message.
      queue = "hello",
      no_ack = True)

print("[*] Waiting for messages. To Exit press CTRL+C")
channel.start_consuming()

用rabbitmq中的fanout模式實(shí)現(xiàn)廣播模式

1) fanout_rabbit_publish.py

# Author : Xuefeng

import pika
import sys

# 廣播模式:
# 生產(chǎn)者發(fā)送一條消息,所有的開(kāi)通鏈接的消費(fèi)者都可以接收到消息

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()
channel.exchange_declare(exchange="logs",
       type="fanout")
message = ' '.join(sys.argv[1:]) or "info:Hello world!"
channel.basic_publish(
 exchange="logs",
 routing_key="",
 body=message
)
print("[x] Send %r" % message)

connection.close()

2) fanout_rabbit_consumer.py

# Author : Xuefeng


import pika
import sys

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()
# exclusive 排他,唯一的 隨機(jī)生成queue
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
print("Random queue name:", queue_name)

channel.queue_bind(exchange="logs",
     queue=queue_name)


def callback(ch, method, properties, body):
 '''
 Handle the recieved data
 :param ch: The address of the channel
 :param method: Information about the connection
 :param properties:
 :param body:
 :return:
 '''
 print("------>", ch, method, properties )
 print("[x] Recieved %r" % body)
 # ack by ourself
 ch.basic_ack(delivery_tag = method.delivery_tag)

# no_ack = True represent that the message cannot be transfor to next consumer,
# when the current consumer is stop by accident.
channel.basic_consume(callback,  # If have recieved message, enable the callback() function to handle the message.
      queue = "hello",
      no_ack = True)

print("[*] Waiting for messages. To Exit press CTRL+C")
channel.start_consuming()

用rabbitmq中的direct模式實(shí)現(xiàn)消息過(guò)濾模式

1) direct_rabbit_publisher.py

# Author : Xuefeng
import pika
import sys

# 消息過(guò)濾模式:
# 生產(chǎn)者發(fā)送一條消息,通過(guò)severity優(yōu)先級(jí)來(lái)確定是否可以接收到消息

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()
channel.exchange_declare(exchange="direct_logs",
       type="direct")
severity = sys.argv[1] if len(sys.argv) > 1 else "info"
message = ' '.join(sys.argv[2:]) or "info:Hello world!"

channel.basic_publish(
 exchange="direct_logs",
 routing_key=severity,
 body=message
)
print("[x] Send %r:%r" % (severity, message))

connection.close()

2) direct_rabbit_consumer.py

# Author : Xuefeng

import pika
import sys

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()

channel.exchange_declare(exchange="direct_logs",
       type="direct")

# exclusive 排他,唯一的 隨機(jī)生成queue
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
print("Random queue name:", queue_name)

severities = sys.argv[1:]
if not severities:
 sys.stderr.write("Usage:%s [info] [warning] [error]\n" % sys.argv[0])
 sys.exit(1)

for severity in severities:
 channel.queue_bind(exchange="direct_logs",
      queue=queue_name,
      routing_key=severity)
 


def callback(ch, method, properties, body):
 '''
 Handle the recieved data
 :param ch: The address of the channel
 :param method: Information about the connection
 :param properties:
 :param body:
 :return:
 '''
 print("------>", ch, method, properties )
 print("[x] Recieved %r" % body)
 # ack by ourself
 ch.basic_ack(delivery_tag = method.delivery_tag)

# no_ack = True represent that the message cannot be transfor to next consumer,
# when the current consumer is stop by accident.
channel.basic_consume(callback,  # If have recieved message, enable the callback() function to handle the message.
      queue = "hello",
      no_ack = True)

print("[*] Waiting for messages. To Exit press CTRL+C")
channel.start_consuming() 


用rabbitmq中的topic模式實(shí)現(xiàn)細(xì)致消息過(guò)濾模式

1) topic_rabbit_publisher.py

# Author : Xuefeng

import pika
import sys

# 消息細(xì)致過(guò)濾模式:
# 生產(chǎn)者發(fā)送一條消息,通過(guò)運(yùn)行腳本 *.info 等確定接收消息類型進(jìn)行對(duì)應(yīng)接收
connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()
channel.exchange_declare(exchange="topic_logs",
       type="topic")
binding_key = sys.argv[1] if len(sys.argv) > 1 else "info"
message = ' '.join(sys.argv[2:]) or "info:Hello world!"

channel.basic_publish(
 exchange="topic_logs",
 routing_key=binding_key,
 body=message
)
print("[x] Send %r:%r" % (binding_key, message))

connection.close()

2) topic_rabbit_consumer.py

# Author : Xuefeng

import pika
import sys

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()

channel.exchange_declare(exchange="topic_logs",
       type="topic")

# exclusive 排他,唯一的 隨機(jī)生成queue
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
print("Random queue name:", queue_name)

binding_keys = sys.argv[1:]
if not binding_keys:
 sys.stderr.write("Usage:%s [info] [warning] [error]\n" % sys.argv[0])
 sys.exit(1)

for binding_key in binding_keys:
 channel.queue_bind(exchange="topic_logs",
      queue=queue_name,
      routing_key=binding_key)


def callback(ch, method, properties, body):
 '''
 Handle the recieved data
 :param ch: The address of the channel
 :param method: Information about the connection
 :param properties:
 :param body:
 :return:
 '''
 print("------>", ch, method, properties)
 print("[x] Recieved %r" % body)
 # ack by ourself
 ch.basic_ack(delivery_tag=method.delivery_tag)


# no_ack = True represent that the message cannot be transfor to next consumer,
# when the current consumer is stop by accident.
channel.basic_consume(callback, # If have recieved message, enable the callback() function to handle the message.
      queue="hello",
      no_ack=True)

print("[*] Waiting for messages. To Exit press CTRL+C")
channel.start_consuming()

用rabbitmq實(shí)現(xiàn)rpc操作

1) Rpc_rabbit_client.py

# Author : Xuefeng

import pika
import time
import uuid

class FibonacciRpcClient(object):
 def __init__(self):
  self.connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"))
  self.channel = self.connection.channel()
  result = self.channel.queue_declare(exclusive=True)
  self.callback_queue = result.method.queue  # 隨機(jī)的生成一個(gè)接收命令執(zhí)行結(jié)果的隊(duì)列
  self.channel.basic_consume(self.on_response, # 只要收到消息就調(diào)用
         no_ack=True,
         queue=self.callback_queue)

 def on_response(self, ch, method, props, body):
  if self.corr_id == props.correlation_id:
   self.response = body

 def call(self,n):
  self.response = None
  self.corr_id = str(uuid.uuid4())
  self.channel.basic_publish(
   exchange="",
   routing_key="rpc_queue",
   properties=pika.BasicPropreties(
    rely_to=self.callback_queue,
    correlation_id=self.corr_id   # 通過(guò)隨機(jī)生成的ID來(lái)驗(yàn)證指令執(zhí)行結(jié)果與指令的匹配性
   ),
   body=str(n)
  )
  while self.response is None:
   self.connection.process_data_events() # 非阻塞版的start_consume,有沒(méi)有消息都繼續(xù)
   print("no message...")
   time.sleep(0.5)
  return int(self.response)

fibonacci_rcp = FibonacciRpcClient()

print("[x] Requesting fib(30)")
response = fibonacci_rcp.call(30)
print("[x] Rec %r" % response)

2) Rpc_rabbit_server.py

# Author : Xuefeng

import pika
import sys

connection = pika.BlockingConnection(pika.Connection.Parameters(
 "localhost"
))
# statement a channel
channel = connection.channel()

channel.queue_declare(queue="rpc_queue")

def fib(n):
 if n == 0:
  return 0
 elif n == 1:
  return 1
 else:
  return fib(n-1)+fib(n-2)

def on_request(ch, method, props, body):
 n = int(body)
 print("[.] fib(%s)" % n)
 response = fib(n)
 ch.basic_publish(
  exchange="",
  routing_key=props.rely_to,
  properties=pika.BasicPropreties(correlation_id=\
          props.correlation),
  body = str(body)
 )
 ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request, queue="rpc_queue")

print("[x] Awaiting RPC requests")
channel.start_consumeing()



channel.exchange_declare(exchange="direct_logs",
       type="direct")

# exclusive 排他,唯一的 隨機(jī)生成queue
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
print("Random queue name:", queue_name)

severities = sys.argv[1:]

到此這篇關(guān)于Python RabbitMQ實(shí)現(xiàn)簡(jiǎn)單的進(jìn)程間通信示例的文章就介紹到這了,更多相關(guān)Python RabbitMQ進(jìn)程間通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python繪制直方圖的方法

    python繪制直方圖的方法

    這篇文章主要為大家詳細(xì)介紹了python繪制直方圖的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • 解決pycharm不能自動(dòng)保存在遠(yuǎn)程linux中的問(wèn)題

    解決pycharm不能自動(dòng)保存在遠(yuǎn)程linux中的問(wèn)題

    這篇文章主要介紹了解決pycharm不能自動(dòng)保存在遠(yuǎn)程linux中的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • 使用python實(shí)現(xiàn)三維圖可視化

    使用python實(shí)現(xiàn)三維圖可視化

    這篇文章主要介紹了使用python實(shí)現(xiàn)三維圖可視化,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-04-04
  • Django+JS 實(shí)現(xiàn)點(diǎn)擊頭像即可更改頭像的方法示例

    Django+JS 實(shí)現(xiàn)點(diǎn)擊頭像即可更改頭像的方法示例

    這篇文章主要介紹了Django+JS 實(shí)現(xiàn)點(diǎn)擊頭像即可更改頭像的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-12-12
  • python字典值排序并取出前n個(gè)key值的方法

    python字典值排序并取出前n個(gè)key值的方法

    今天小編就為大家分享一篇python字典值排序并取出前n個(gè)key值的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • Python 2.x如何設(shè)置命令執(zhí)行的超時(shí)時(shí)間實(shí)例

    Python 2.x如何設(shè)置命令執(zhí)行的超時(shí)時(shí)間實(shí)例

    這篇文章主要給大家介紹了關(guān)于Python 2.x如何設(shè)置命令執(zhí)行超時(shí)時(shí)間的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-10-10
  • Python 從相對(duì)路徑下import的方法

    Python 從相對(duì)路徑下import的方法

    今天小編就為大家分享一篇Python 從相對(duì)路徑下import的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-12-12
  • Python學(xué)習(xí)筆記嵌套循環(huán)詳解

    Python學(xué)習(xí)筆記嵌套循環(huán)詳解

    這篇文章主要介紹了Python學(xué)習(xí)筆記嵌套循環(huán)詳解,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-07-07
  • Python中input()函數(shù)的用法實(shí)例小結(jié)

    Python中input()函數(shù)的用法實(shí)例小結(jié)

    我們編寫(xiě)的大部分程序,都需要讀取輸入并對(duì)其進(jìn)行處理,而基本的輸入操作是從鍵盤(pán)鍵入數(shù)據(jù),Python從鍵盤(pán)鍵入數(shù)據(jù),大多使用其內(nèi)置的input()函數(shù),下面這篇文章主要給大家介紹了關(guān)于Python中input()函數(shù)用法的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • python繪制隨機(jī)網(wǎng)絡(luò)圖形示例

    python繪制隨機(jī)網(wǎng)絡(luò)圖形示例

    今天小編就為大家分享一篇python繪制隨機(jī)網(wǎng)絡(luò)圖形示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-11-11

最新評(píng)論

左权县| 紫金县| 逊克县| 阿图什市| 绥滨县| 漳平市| 咸宁市| 延津县| 开封县| 淮安市| 大石桥市| 迁安市| 霍州市| 白河县| 黄龙县| 丽水市| 佛教| 鹿邑县| 和硕县| 陆河县| 浦城县| 日喀则市| 东兴市| 黎城县| 泰安市| 外汇| 利津县| 顺平县| 公安县| 毕节市| 若羌县| 吉木乃县| 林口县| 平阴县| 碌曲县| 塔城市| 香港 | 左权县| 黄梅县| 利川市| 漯河市|