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
38
39
40
41
42
|
#!/usr/bin/python3
import pika
import json
def read_json(file_name):
# 读取 JSON 文件内容
with open(file_name, 'r') as file:
data_str = file.read()
data = json.loads(data_str)
return data
credentials = pika.PlainCredentials('guest', 'guest')
parameters = pika.ConnectionParameters('127.0.0.1',
port=5673, # RabbitMQ 服务器的端口
virtual_host='/',
credentials=credentials)
# 连接到 RabbitMQ 服务器
connection = pika.BlockingConnection(parameters)
# 连接到 RabbitMQ 服务器
channel = connection.channel()
print("channel:",channel)
# 声明一个队列
channel.queue_declare(queue='a1',auto_delete=True, arguments={'x-message-ttl': 10001})
# 发送消息
channel_id = 3
# 发布一条消息,指定 channel_id
#curbody='{"msgType":"TestMessage","messageData":{"messageTime":"2024-04-10 11:24:22"}}'
curbody_json=read_json("/tmp/test.json")
curbody = json.dumps(curbody_json)
print("curbody:",curbody)
channel.basic_publish(exchange='', routing_key='a1', body=curbody, properties=pika.BasicProperties(
content_type='application/json',
delivery_mode=2, # make message persistent
headers={'channel_id': channel_id}))
print(" Sent 'RabbitMQ msg!'")
# 关闭连接
connection.close()
|