public static void GetSmsUp() { Console.WriteLine("Enter the save path:"); string savePath; savePath = Console.ReadLine(); SaveTask.Init(savePath); InitData(); for (int i = 0; i < maxThread; i++) { MainTask testTask = new MainTask("PullMessageTask-thread-" + i, messageType, queueName, acsClient); Thread t = new Thread(new ThreadStart(testTask.Handle)); //启动线程 t.Start(); } Console.WriteLine("Any Key To EXIT"); Console.ReadKey(); SaveTask.Close(); Environment.Exit(0); }
/// 处理消息 public void Handle() { while (true) { try { QueryTokenForMnsQueueResponse.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 具体消费逻辑,待客户自己实现. if (SaveTask.WriteRecord(orgStr)) { //消费成功的前提下删除消息 queue.DeleteMessage(messages[i].ReceiptHandle); } } catch (Exception e) { Console.WriteLine("ERR: " + e.Message); } } } catch (Exception e) { Console.WriteLine("Handle exception: " + e.Message); } Thread.Sleep(sleepTime); } }