我在我的Linux机器上安装了rabbitmq-server。我在RABBIRMQ的官方网站上安装了AMQP-CPP客户端库。enter link description here
现在我想作为生产者连接到rabbitmq-server,并希望在队列中发布消息。 我已经建立了一个连接处理程序,主文件如下:
int main(int argc, char ** argv) {
const std:: string exchange = "my-exchange";
const std:: string routingKey = "my-routing-key";
const char* message = "HELLO WORLD";
MyTcpHandler myHandler;
// address of the server
cout << "TcpHandler object created.." << endl;
AMQP:: Address address("amqp://guest:guest@localhost:5672");
//("amqp://guest:guest@localhost/vhost");
cout << "address object created.." << endl;
// create a AMQP connection object
AMQP:: TcpConnection connection(& myHandler, address);
cout << "connection object created.." << endl;
// and create a channel
AMQP:: TcpChannel channel(& connection);
cout << "channel object created.." << endl;
// use the channel object to call the AMQP method you like
channel.declareExchange("my-exchange", AMQP:: fanout);
channel.declareQueue("my-queue");
channel.bindQueue("my-exchange", "my-queue", "my-routing-key");
cout << "before publish.." << endl;
// start a transaction
channel.startTransaction();
int pubVal = channel.publish(exchange, routingKey, message);
我无法连接到队列。也许我没有实施&#34;监控&#34; MyTcpHandler类中正确的方法: virtual void monitor(AMQP :: TcpConnection * connection,int fd,int flags) 请帮忙吗?
答案 0 :(得分:0)
这有点迟了。对我而言,AMQP-CPP包装器始终也是噩梦。好吧,如果您不想要某些非常特定的功能,则可以使用其他c ++包装器来代替https://github.com/alanxz/SimpleAmqpClient
//SimpleAMQPClient Producer
Channel::ptr_t connection = Channel::Create("MQ server IP",5672,"username","password");
string producerMessage = "this is a test message";
connection->BasicPublish("exchange","routing key",BasicMessage::Create(producerMessage));
完成了!!!
现在,如果您坚持使用AMQP-CPP,上面的代码中我想指出的几件事。
AMQP::Address address("amqp://guest:guest@localhost:5672");
我不确定该地址是否是服务器运行的地址,请尝试在端口为15672的浏览器中输入该地址,看看是否能获得服务器的UI。
amqp:// guest:guest @ localhost:15672
// use the channel object to call the AMQP method you like
channel.declareExchange("my-exchange", AMQP::fanout);
channel.declareQueue("my-queue");
channel.bindQueue("my-exchange", "my-queue", "my-routing-key");
此代码将在每次运行时声明一个交换并创建一个队列,大多数情况下它将仅在第一次运行,然后每次都会发生名称冲突(如果我的假设正确的话)
更好的方法是从Rabbit-MQ服务器UI创建队列。 确保已安装rabbitMQ-server(RabbitMQ-C是客户端)https://www.rabbitmq.com/download.html#server-installation-guides 并通过c ++代码发送消息。
现在您需要做的就是打开浏览器并输入以下链接
运行服务器的IP: 1 5672
对于本地,应为127.0.0.1:15672(请注意端口号及其15672),然后输入用户名和密码。
//SimpleAMQPClient Consumer
string consumer_tag=connection->BasicConsume("queue","",true,false);
Envelope::ptr_t envelope = connection->BasicConsumeMessage(consumer_tag);
BasicMessage::ptr_t bodyBasicMessage=envelope->Message();
string messageBody=bodyBasicMessage->Body();
上面的simpleAMQPClient代码是我的应用程序中的工作副本。
希望有帮助。