// 引入必要的头文件#include <iostream>#include <string>#include <amqpcpp.h>#include <amqpcpp/libboostasio.h>
// 定义连接信息const std::string conn_str = "amqp://username:password@host:port/vhost";
// 创建一个继承自AMQP::ConnectionHandler类并重写其方法的连接处理程序class MyConnectionHandler : public AMQP::ConnectionHandler {public: // 覆盖onData函数以处理收到数据的情况 virtual void onData(AMQP::Connection *connection, const char *data, size_t size) { // 解码消息 AMQP::Envelope envelope; if (envelope.decode(data, size)) { // 打印接收到的数据 std::cout << "Received message with routing key '" << envelope.routingkey() << "' on exchange '" << envelope.exchange() << "': " << envelope.message() << std::endl; } else { std::cerr << "Error decoding message" << std::endl; } }};
int main() { // 创建一个事件循环 boost::asio::io_service io_service;
// 创建一个新的连接 AMQP::TcpConnection connection(&io_service, AMQP::Address(conn_str));
// 设置一个连接处理程序 MyConnectionHandler handler; connection.setConnectionHandler(&handler);
// 创建一个通道 AMQP::TcpChannel channel(&connection);
// 声明一个交换机 channel.declareExchange("my_exchange", AMQP::fanout);
// 声明一个队列 channel.declareQueue("my_queue");
// 将队列绑定到交换机上 channel.bindQueue("my_exchange", "my_queue", "");
// 发布一条消息 std::string message = "Hello World!"; channel.publish("my_exchange", "", message);
// 启动事件循环 io_service.run();
return 0;}
评论