Last active
June 2, 2019 04:03
-
-
Save guerbai/f61fb803b60e85fd40e52bcfd68e27dc to your computer and use it in GitHub Desktop.
rabbitmq使用示例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from librabbitmq import Connection | |
rconf = { | |
"host": "localhost", | |
"userid": "guest", | |
"password": "guest", | |
"vhost": "/", | |
"exchange": "kong", | |
"extype": "direct" | |
} | |
connection = Connection( | |
host=rconf["host"], | |
virtual_host=rconf["vhost"], | |
userid=rconf["userid"], | |
password=rconf["password"]) | |
channel = connection.channel() | |
channel.exchange_declare(exchange=rconf["exchange"], type=rconf["extype"]) | |
channel.basic_publich( | |
exchange=rconf["exchange"], | |
routing_key=routing, | |
body=str(body), | |
delivery_mode=2) # delivery_mode=2与durable对应 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from librabbitmq import Connection | |
connection = Connection( | |
host=rconf["host"], | |
virtual_host=rconf["vhost"], | |
userid=rconf["userid"], | |
password=rconf["password"]) | |
channel = connection.channel() | |
channel.exchange_declare(exchange=rconf["exchange"], type=rconf["extype"]) | |
channel.queue_declare(queue="queue_name", durable=True) # durable=True将消息进行持久化 | |
channel.queue_bind(exchange=rconf["exchange"], queue="queue_name", | |
routing_key=routing) | |
channel.basic_qos(prefetch_count=1) | |
channel.basic_consume(callback=callback, | |
queue="queue_name") # 若加参数no_ack=True,则若某worker在处理消息时,worker挂掉,则信息会丢失 | |
while True: | |
connection.drain_events() | |
def callback(message): | |
params = ast.literal_eval(str(message.body)) | |
print params | |
message.ack() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment