各种消息类型使用
时间: 2023-07-11 19:10:46 浏览: 46
以下是各种消息类型的使用方法:
1. 简单消息
发送消息:
```
channel.basic_publish(exchange='', routing_key='queue_name', body='message_body')
```
接收消息:
```
def callback(ch, method, properties, body):
print("Received message:", body.decode())
channel.basic_consume(queue='queue_name', on_message_callback=callback, auto_ack=True)
channel.start_consuming()
```
2. 消息确认
发送消息:
```
channel.basic_publish(exchange='', routing_key='queue_name', body='message_body', properties=pika.BasicProperties(delivery_mode=2))
```
接收消息:
```
def callback(ch, method, properties, body):
do_something()
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='queue_name', on_message_callback=callback)
channel.start_consuming()
```
3. 消息持久化
发送消息:
```
channel.basic_publish(exchange='', routing_key='queue_name', body='message_body', properties=pika.BasicProperties(delivery_mode=2))
```
接收消息:
```
def callback(ch, method, properties, body):
do_something()
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='queue_name', on_message_callback=callback)
channel.start_consuming()
```
4. 消息优先级
发送消息:
```
channel.basic_publish(exchange='', routing_key='queue_name', body='message_body', properties=pika.BasicProperties(priority=1))
```
接收消息:
```
def callback(ch, method, properties, body):
do_something()
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='queue_name', on_message_callback=callback)
channel.start_consuming()
```
5. 延迟消息
发送消息:
```
channel.basic_publish(exchange='', routing_key='queue_name', body='message_body', properties=pika.BasicProperties(expiration='10000'))
```
其中,`expiration`属性指定了消息的过期时间,单位为毫秒。
接收消息同简单消息。
以上代码示例使用了pika库来操作RabbitMQ,具体使用方法可以参考pika官方文档。