edit-icon download-icon

Send and receive normal messages

Last Updated: Jun 19, 2018

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

Subscribe to Normal Messages

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

Thank you! We've received your feedback.