rabbitmq发送消息代码
时间: 2023-10-04 22:14:20 浏览: 84
rabbitmq代码.zip
5星 · 资源好评率100%
以下是使用Python发送消息到RabbitMQ的示例代码:
```python
import json
import pika
import datetime
def send_message():
for i in range(10):
message = json.dumps({'id': "10000%s" % i, "amount": 100 * i, "name":"tony", "createtime": str(datetime.datetime.now())})
producer(message)
def producer(message):
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', port=5672, credentials=pika.PlainCredentials('guest', 'guest')))
channel = connection.channel()
channel.queue_declare(queue='tester')
channel.basic_publish(exchange='', routing_key='tester', body=message)
connection.close()
if __name__ == "__main__":
send_message()
```
这段代码使用pika库来与RabbitMQ建立连接并发送消息。首先,我们通过指定主机、端口和凭据来创建一个连接。然后,我们创建一个通道和一个名为'tester'的队列。最后,我们调用`basic_publish`方法将消息发送到队列中。注意,这里的`exchange`参数为空字符串,表示使用默认的exchange。完整的代码可以根据你的具体需求进行调整和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Python之Rabbitmq发送消息](https://blog.csdn.net/weixin_41754309/article/details/107070171)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文