rabbit持久化消息示例
consumer.cpp
#include "AMQPcpp.h" #include <thread> #include <string> #include <iostream> #include <chrono> int onCancel(AMQPMessage * message) { std::cout << "cancel tag=" << message->getDeliveryTag() << std::endl; return 0; } int onMessage(AMQPMessage * message) { uint32_t j = 0; char * data = message->getMessage(&j); if (data) std::cout << data << std::endl; AMQPQueue * q = message->getQueue(); std::cout << "ConsumerTag:" << q->getConsumerTag().c_str(); std::cout << " tag=" << message->getDeliveryTag() << " content-type:" << message->getHeader("Content-type"); std::cout << " encoding:" << message->getHeader("Content-encoding") << " mode=" << message->getHeader("Delivery-mode") << std::endl; return 0; }; void func_consume() { try { AMQP amqp("admin:admin@localhost:5672");//"username:passwd@ip:port",默认vhost "/" AMQPQueue * queue = amqp.createQueue(); //队列属性参数 //AMQP_PASSIVE true:判断是否存在, 不存在抛出异常 false: 不存在则创建 //AMQP_DURABLE true:队列持久化, 即rabbitmq服务器重启后该队列仍存在 //AMQP_AUTODELETE true:当没有消费者时, 服务器自动删除该队列 //AMQP_EXCLUSIVE true:专用队列,连接断开后就删除该队列 short queParam = AMQP_DURABLE; queue->Declare("queueTest1", queParam); std::string key = ""; queue->Bind("exTest1", key); queue->setConsumerTag("test1"); queue->addEvent(AMQP_MESSAGE, onMessage); queue->addEvent(AMQP_CANCEL, onCancel); queue->Consume(AMQP_NOACK); } catch (AMQPException e) { std::cout << "func_consume: " << e.getMessage() << std::endl; } } int main() { std::thread threadCons(func_consume); threadCons.join(); return 0; }
produce.cpp
#include "AMQPcpp.h" #include <thread> #include <string> #include <iostream> #include <chrono> void func_product() { try { AMQP amqp("admin:admin@localhost:5672");//"username:passwd@ip:port",默认vhost "/" AMQPExchange* exchange = amqp.createExchange(); //交换机属性参数 //AMQP_PASSIVE true:判断是否存在, 不存在抛出异常 false: 不存在则创建 //AMQP_DURABLE true:交换机持久化, 即rabbitmq服务器重启后该交换机仍存在 //AMQP_AUTODELETE true:当没有消费者时, 服务器自动删除该交换机 short exParams = 0; exchange->Declare("exTest1", "fanout", exParams); exchange->setHeader("Delivery-mode", 2); // 1:消息不持久化 2:消息持久化 exchange->setHeader("Content-type", "text/plain"); exchange->setHeader("Content-encoding", "UTF-8"); while (1) { std::this_thread::sleep_for(std::chrono::milliseconds(2000)); static int num = 0; std::string message = "message" + std::to_string(num); exchange->Publish(message, ""); std::cout << "publish :" << message.c_str() << std::endl; num++; } } catch (AMQPException e) { std::cout <<"func_product: "<< e.getMessage() << std::endl; } } int main() { std::thread threadProd(func_product); threadProd.join(); return 0; }
编译命令