All Products
Search
Document Center

Send and receive normal messages

Last Updated: Mar 29, 2019

Send normal messages

Execute the following code to send messages. Set parameters correctly according to the instructions.

  1. using System;
  2. using ons;
  3. public class ProducerExampleForEx
  4. {
  5. public ProducerExampleForEx()
  6. {
  7. }
  8. static void Main(string[] args) {
  9. // Configure your account according to the settings in the console.
  10. ONSFactoryProperty factoryInfo = new ONSFactoryProperty();
  11. // The AccessKeyId you created in the Alibaba Cloud console for identity authentication.
  12. factoryInfo.setFactoryProperty(ONSFactoryProperty.AccessKey, "Your access key");
  13. // The AccessKeySecret you created in the Alibaba Cloud console for identity authentication.
  14. factoryInfo.setFactoryProperty(ONSFactoryProperty.SecretKey, "Your access secret");
  15. // The group ID you created in the console.
  16. factoryInfo.setFactoryProperty(ONSFactoryProperty.ProducerId, "GID_example");
  17. // The topic you created in the console.
  18. factoryInfo.setFactoryProperty(ONSFactoryProperty.PublishTopics, "T_example_topic_name");
  19. // Set the TCP endpoint: Go to the **Instances** page in the RocketMQ console, and view the endpoint in the **Endpoint Information** area.
  20. factoryInfo.setFactoryProperty(ONSFactoryProperty.NAMESRV_ADDR, "NameSrv_Addr");
  21. // Set the log path.
  22. factoryInfo.setFactoryProperty(ONSFactoryProperty.LogPath, "C://log");
  23. // Create producer instances.
  24. // Note: Producer instances are thread-secure and can be used to send messages of different topics. Each of your threads
  25. // needs only one producer instance.
  26. Producer producer = ONSFactory.getInstance().createProducer(factoryInfo);
  27. // Start the instance at the client.
  28. producer.start();
  29. // Create message objects.
  30. Message msg = new Message(factoryInfo.getPublishTopics(), "tagA", "Example message body");
  31. msg.setKey(Guid.NewGuid(). ToString());
  32. for (int i = 0; i < 32; i++) {
  33. try
  34. {
  35. SendResultONS sendResult = producer.send(msg);
  36. Console.WriteLine("send success {0}", sendResult.getMessageId());
  37. }
  38. catch (Exception ex)
  39. {
  40. Console.WriteLine("send failure{0}", ex.ToString());
  41. }
  42. }
  43. // Disable the producer instance when the thread is about to exit.
  44. producer.shutdown();
  45. }
  46. }

Subscribe to normal messages

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