public QueryTokenForMnsQueue_MessageTokenDTO GetTokenByMessageType(IAcsClient acsClient, String messageType) { QueryTokenForMnsQueueRequest request = new QueryTokenForMnsQueueRequest { MessageType = messageType }; QueryTokenForMnsQueueResponse queryTokenForMnsQueueResponse = acsClient.GetAcsResponse(request); QueryTokenForMnsQueue_MessageTokenDTO token = queryTokenForMnsQueueResponse.MessageTokenDTO; return(token); }
/// 处理消息 public void Handle() { while (true) { try { QueryTokenForMnsQueue_MessageTokenDTO token = null; Queue queue = null; lock (o) { if (tokenMap.ContainsKey(messageType)) { token = tokenMap[messageType]; } if (queueMap.ContainsKey(QueueName)) { queue = queueMap[QueueName]; } TimeSpan ts = new TimeSpan(0); if (token != null) { DateTime b = Convert.ToDateTime(token.ExpireTime); DateTime c = Convert.ToDateTime(DateTime.Now); ts = b - c; } if (token == null || ts.TotalSeconds < bufferTime || queue == null) { token = GetTokenByMessageType(AcsClient, messageType); IMNS client = new MNSClient(token.AccessKeyId, token.AccessKeySecret, mnsAccountEndpoint, token.SecurityToken); queue = client.GetNativeQueue(QueueName); if (tokenMap.ContainsKey(messageType)) { tokenMap.Remove(messageType); } if (queueMap.ContainsKey(QueueName)) { queueMap.Remove(QueueName); } tokenMap.Add(messageType, token); queueMap.Add(QueueName, queue); } } BatchReceiveMessageResponse batchReceiveMessageResponse = queue.BatchReceiveMessage(16); List <Message> messages = batchReceiveMessageResponse.Messages; for (int i = 0; i <= messages.Count - 1; i++) { try { byte[] outputb = Convert.FromBase64String(messages[i].Body); string orgStr = Encoding.UTF8.GetString(outputb); Console.WriteLine(orgStr); // TODO 具体消费逻辑,待客户自己实现. // 消费成功的前提下删除消息 queue.DeleteMessage(messages[i].ReceiptHandle); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } catch (Exception e) { //Console.WriteLine(e.ToString()); } Thread.Sleep(sleepTime); } }