Python-RabbitMQ(简单发送模型)

RabbitMQ须要 erlang 和pikapython

1.RabbitMQ和erlang版本必须匹配,不然就报没有进程错误windows

2.RabbitMQ的erlang.cookie和windows下的erlang.cookie必须一致cookie

在windows安装RabbitMQ须要配置环境变量,一个是erlang环境变量,一个是RabbitMQ的环境变量切记!函数

发送端:生产者spa

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import  pika
 
connection  =  pika.BlockingConnection(
     pika.ConnectionParameters( 'localhost' ))
channel  = connection.channel() #声明一个管道,在管道里发消息
 
#声明queue
channel.queue_declare(queue = 'hello' ) #在管道里还得声明一个队列
 
 
channel.basic_publish(exchange = '',
                       routing_key = 'hello' , #就是列队queue名字
                       body = 'Hello World' #消息内容
                       )
print ( " [x] Sent 'Hello World!'" )
connection.close() #不用关闭管道,关闭链接就行

 接收端:消费者code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import  pika
 
# 创建到达RabbitMQ Server的connection
# 此处RabbitMQ Server位于本机-localhost
connection  =  pika.BlockingConnection(pika.ConnectionParameters(
     'localhost' ))
channel  =  connection.channel()
 
# 声明queue,确认要从中接收message的queue
# queue_declare函数是幂等的,可运行屡次,但只会建立一次
# 若能够确信queue是已存在的,则此处可省略该声明,如producer已经生成了该queue
# 但在producer和consumer中重复声明queue是一个好的习惯
channel.queue_declare(queue = 'hello' )
 
print ( ' [*] Waiting for messages. To exit press CTRL+C' )
 
 
# 定义回调函数
# 一旦从queue中接收到一个message回调函数将被调用
# ch:channel
# method:
# properties:
# body:message
def  callback(ch, method, properties, body):
     print ( " [x] Received %r"  %  body)
 
 
# 从queue接收message的参数设置
# 包括从哪一个queue接收message,用于处理message的callback,是否要确认message
# 默认状况下是要对消息进行确认的,以防止消息丢失。
# 此处将no_ack明确指明为True,不对消息进行确认。
channel.basic_consume(callback,
                       queue = "hello" ,
                       no_ack = True )
 
# 开始循环从queue中接收message并使用callback进行处理
channel.start_consuming()
相关文章
相关标签/搜索