All Products
Document Center

Send and receive normal messages

Last Updated: Mar 29, 2019

Send Normal Messages

Refer to the example below to send messages.

  1. #include "ONSFactory.h"
  2. #include "ONSClientException.h"
  3. using namespace ons;
  4. int main()
  5. {
  6. //Create producer and configure parameters required for sending messages;
  7. ONSFactoryProperty factoryInfo;
  8. factoryInfo.setFactoryProperty(ONSFactoryProperty::PublishTopics,"XXX" );// Message content
  9. factoryInfo.setFactoryProperty(ONSFactoryProperty::MsgContent, "XXX");//Message content
  10. factoryInfo.setFactoryProperty(ONSFactoryProperty::AccessKey, "XXX");//AccessKey, Alibaba Cloud ID verification, which is created on Alibaba Cloud Management Console
  11. factoryInfo.setFactoryProperty(ONSFactoryProperty::SecretKey, "XXX" );//SecretKey, Alibaba Cloud ID verification, which is created on Alibaba Cloud Management Console
  12. //create producer;
  13. Producer *pProducer = ONSFactory::getInstance()->createProducer(factoryInfo);
  14. // Before sending messages, the start method must be called once to start the producer;
  15. pProducer->start();
  16. Message msg(
  17. //Message Topic
  18. factoryInfo.getPublishTopics(),
  19. //Message tag, which is similar to tag in Gmail, and is used to classify messages. Consumers can then set filtering conditions for messages to be filtered in MQ broker.
  20. "TagA",
  21. //Message Body, which cannot be null. Serialization and deserialization methods need to be negotiated and remain consistent between the producer and the consumer.
  22. factoryInfo.getMessageContent()
  23. );
  24. // The setting represents the key business property of the message, so please keep it globally unique.
  25. // You can query a message and resend it through the MQ console when you cannot receive the message properly.
  26. // Note: Normal sessage sending and receiving will not be affected if message key is not configured.
  27. msg.setKey("ORDERID_100");
  28. // If no exceptions are thrown, then the message is sent successfully.
  29. try
  30. {
  31. SendResultONS sendResult = pProducer->send(msg);
  32. }
  33. catch(ONSClientException & e)
  34. {
  35. //Customize the details for processing the exception
  36. }
  37. // The object Producer must be destroyed before exiting the application. Otherwise there will be memory leakage.
  38. pProducer->shutdown();
  39. return 0;
  40. }

Subscribe to Normal Messages

For instructions and sample codes of subscribing to standard messages, see Subscribe to messages.