edit-icon download-icon

Send and receive normal messages

Last Updated: Jul 17, 2018

Send Normal Messages

You can execute the following code to send messages. Before you start, set related parameters correctly according to the instructions.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. using ons;
  7. namespace ons
  8. {
  9. class onscsharp
  10. {
  11. static void Main(string[] args)
  12. {
  13. // A mandatory parameter which is required for the creation and normal operation of producer
  14. ONSFactoryProperty factoryInfo = new ONSFactoryProperty();
  15. factoryInfo.setFactoryProperty(factoryInfo.ProducerId, "PID_xxxx “);// The producer ID you have created on the MQ console
  16. factoryInfo.setFactoryProperty(factoryInfo.PublishTopics, "xxx”);// The topic you have created on the MQ console
  17. factoryInfo.setFactoryProperty(factoryInfo.MsgContent, "xxx”);// msg content
  18. factoryInfo.setFactoryProperty(factoryInfo.AccessKey, "xxx”);// AccessKey, Alibaba Cloud ID verification, which is created on Alibaba Cloud Management Console
  19. factoryInfo.setFactoryProperty(factoryInfo.SecretKey,"xxx”);// SecretKey, Alibaba Cloud ID verification, which is created on Alibaba Cloud Management Console
  20. // Create a producer
  21. ONSFactory onsfactory = new ONSFactory();
  22. Producer pProducer = onsfactory.getInstance().createProducer(factoryInfo);
  23. // Before sending messages, the start method must be called once to start the producer.
  24. pProducer.start();
  25. Message msg = new Message(
  26. // Message Topic
  27. factoryInfo.getPublishTopics(),
  28. // Message Tag
  29. "TagA",
  30. // Message Body
  31. factoryInfo.getMessageContent()
  32. );
  33. // The setting represents the key service property of the message, so please set it as globally unique as possible.
  34. // You can query a message and resend it through the MQ console when you cannot receive the message properly.
  35. // Note: Normal sessage sending and receiving will not be affected if message key is not configured.
  36. msg.setKey("ORDERID_100");
  37. // If no exceptions are thrown, then the message is sent successfully.
  38. try
  39. {
  40. SendResultONS sendResult = pProducer.send(msg);
  41. }
  42. catch(ONSClientException e)
  43. {
  44. // Handle message sending failures
  45. }
  46. // The object Producer must be destroyed before exiting the application. Otherwise there will be memory leakage.
  47. pProducer.shutdown();
  48. }
  49. }
  50. }

Subscribe to normal messages

For instructions and sample code of subscribing to normal messages, see Subscribe to messages.

Thank you! We've received your feedback.