第 4 章 例子
本章演示了通过示例程序使用 AMQ C++。
如需了解更多示例,请参阅 AMQ C++ 示例套件和 Qpid Proton C++ 示例。
注意
本指南中介绍的代码使用 C++11 功能。AMQ C++ 也与 C++03 兼容,但代码需要次要修改。
4.1. 发送消息 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
此客户端程序使用 < connection-url > 连接到服务器,为目标 <address& gt; 创建发件人,发送一条消息,包含 <message-body >、关闭连接并退出。
示例:发送消息
#include <proton/connection.hpp>
#include <proton/container.hpp>
#include <proton/message.hpp>
#include <proton/messaging_handler.hpp>
#include <proton/sender.hpp>
#include <proton/target.hpp>
#include <iostream>
#include <string>
struct send_handler : public proton::messaging_handler {
std::string conn_url_ {};
std::string address_ {};
std::string message_body_ {};
void on_container_start(proton::container& cont) override {
cont.connect(conn_url_);
// To connect with a user and password:
//
// proton::connection_options opts {};
// opts.user("<user>");
// opts.password("<password>");
//
// cont.connect(conn_url_, opts);
}
void on_connection_open(proton::connection& conn) override {
conn.open_sender(address_);
}
void on_sender_open(proton::sender& snd) override {
std::cout << "SEND: Opened sender for target address '"
<< snd.target().address() << "'\n";
}
void on_sendable(proton::sender& snd) override {
proton::message msg {message_body_};
snd.send(msg);
std::cout << "SEND: Sent message '" << msg.body() << "'\n";
snd.close();
snd.connection().close();
}
};
int main(int argc, char** argv) {
if (argc != 4) {
std::cerr << "Usage: send <connection-url> <address> <message-body>\n";
return 1;
}
send_handler handler {};
handler.conn_url_ = argv[1];
handler.address_ = argv[2];
handler.message_body_ = argv[3];
proton::container cont {handler};
try {
cont.run();
} catch (const std::exception& e) {
std::cerr << e.what() << "\n";
return 1;
}
return 0;
}
运行示例
要运行示例程序,请将其复制到本地文件,对其进行编译并从命令行执行。如需更多信息,请参阅 第 3 章 开始使用。
$ g++ send.cpp -o send -std=c++11 -lstdc++ -lqpid-proton-cpp
$ ./send amqp://localhost queue1 hello