第 4 章 例子
本章演示了通过示例程序使用 AMQ Python。
如需了解更多示例,请参阅 AMQ Python 示例套件和 Qpid Proton Python 示例。
4.1. 发送消息 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
此客户端程序使用 < connection-url > 连接到服务器,为目标 <address& gt; 创建发件人,发送一条消息,包含 <message-body >、关闭连接并退出。
示例:发送消息
from __future__ import print_function
import sys
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import Container
class SendHandler(MessagingHandler):
def __init__(self, conn_url, address, message_body):
super(SendHandler, self).__init__()
self.conn_url = conn_url
self.address = address
self.message_body = message_body
def on_start(self, event):
conn = event.container.connect(self.conn_url)
# To connect with a user and password:
# conn = event.container.connect(self.conn_url, user="<user>", password="<password>")
event.container.create_sender(conn, self.address)
def on_link_opened(self, event):
print("SEND: Opened sender for target address '{0}'".format
(event.sender.target.address))
def on_sendable(self, event):
message = Message(self.message_body)
event.sender.send(message)
print("SEND: Sent message '{0}'".format(message.body))
event.sender.close()
event.connection.close()
def main():
try:
conn_url, address, message_body = sys.argv[1:4]
except ValueError:
sys.exit("Usage: send.py <connection-url> <address> <message-body>")
handler = SendHandler(conn_url, address, message_body)
container = Container(handler)
container.run()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
运行示例
要运行示例程序,请将其复制到本地文件,并使用 python 命令调用它。如需更多信息,请参阅 第 3 章 开始使用。
$ python send.py amqp://localhost queue1 hello