參考文檔
https://www.zybuluo.com/iamfox/note/239385
環境准備
1.申請阿里雲賬號,開通消息隊列服務,申請accessKey。
2.SDK導入(c++): ManagedONS.dll, ONSClient4CPP.exp(阿里后台下載)
3.添加引用(c#):ManagedONS.dll
using ons; namespace MQTask { class Program { static void Main(string[] args) { //申請賬號 string ConsumerId = GetConsumerId(); string ProducerId = GetProducerId(); string OrderTopic = ConfigurationSettings.AppSettings["OrderTopic"]; string Topic = ConfigurationSettings.AppSettings["Topic"]; string SecretKey = GetSecretKey(); string AccessKey = GetAccessKey(); //創建工廠 ONSFactoryProperty factoryInfo = new ONSFactoryProperty(); factoryInfo.setFactoryProperty(ONSFactoryProperty.AccessKey, AccessKey); factoryInfo.setFactoryProperty(ONSFactoryProperty.SecretKey, SecretKey); factoryInfo.setFactoryProperty(ONSFactoryProperty.ConsumerId, ConsumerId); factoryInfo.setFactoryProperty(ONSFactoryProperty.ProducerId, ProducerId); factoryInfo.setFactoryProperty(ONSFactoryProperty.PublishTopics, Topic); //創建producer Producer pProducer = ONSFactory.getInstance().createProducer(factoryInfo); //在發送消息前,必須調用start方法來啟動Producer,只需調用一次即可。 pProducer.start(); ////確定消費完成后,調用shutdown函數;在應用退出前,必須銷毀Consumer 對象,否則會導致內存泄露等問題 // pConsumer.shutdown(); } public static SendResultONS sendmsg(Producer pProducer, string topic, string tag, string json, string keys) { string json1 = HttpUtility.UrlEncode(json); Message msg = new Message( //Message Topic topic, //Message Tag,可理解為Gmail中的標簽,對消息進行再歸類,方便Consumer指定過濾條件在ONS服務器過濾 tag, //Message Body,任何二進制形式的數據,ONS不做任何干預,需要Producer與Consumer協商好一致的序列化和反序列化方式 json1 ); // 設置代表消息的業務關鍵屬性,請盡可能全局唯一。 // 以方便您在無法正常收到消息情況下,可通過ONS Console查詢消息並補發。 // 注意:不設置也不會影響消息正常收發 msg.setKey(keys); //發送消息,只要不拋異常就是成功 SendResultONS sendResult = null; try { sendResult = pProducer.send(msg); } catch { //異常處理 return null; } return sendResult; } public static void getmsg(PushConsumer pConsumer) { MessageListener msgListener = new MyMsgListener(); pConsumer.subscribe(Topic, "*", msgListener); } public class MyMsgListener : MessageListener { public MyMsgListener() { } ~MyMsgListener() { } public override ons.Action consume(Message value, ConsumeContext context) { string getTopic = value.getTopic(); string getTag = value.getTag(); string getKey = value.getKey(); string getMsgID = value.getMsgID(); string getBody = value.getBody(); return ons.Action.CommitMessage; } } } }