閱讀230 返回首頁    go 新東方


消費消息示例代碼__Java SDK_SDK使用手冊_消息服務-阿裏雲

消費消息

  1. public class ConsumerDemo {
  2. public static void main(String[] args) {
  3. CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
  4. //this client need only initialize once
  5. MNSClient client = account.getMNSClient();
  6. //循環消費10條消息
  7. try{
  8. CloudQueue queue = client.getQueueRef("TestQueue");
  9. for (int i = 0; i < 10; i++)
  10. {
  11. Message popMsg = queue.popMessage();
  12. if (popMsg != null){
  13. System.out.println("message handle: " + popMsg.getReceiptHandle());
  14. System.out.println("message body: " + popMsg.getMessageBodyAsString());
  15. System.out.println("message id: " + popMsg.getMessageId());
  16. System.out.println("message dequeue count:" + popMsg.getDequeueCount());
  17. //刪除已經消費的消息
  18. queue.deleteMessage(popMsg.getReceiptHandle());
  19. System.out.println("delete message successfully.n");
  20. }
  21. else{
  22. System.out.println("message not exist in TestQueue.n");
  23. }
  24. }
  25. } catch (ClientException ce)
  26. {
  27. System.out.println("Something wrong with the network connection between client and MNS service."
  28. + "Please check your network and DNS availablity.");
  29. ce.printStackTrace();
  30. } catch (ServiceException se)
  31. {
  32. se.printStackTrace();
  33. logger.error("MNS exception requestId:" + se.getRequestId(), se);
  34. if (se.getErrorCode() != null) {
  35. if (se.getErrorCode().equals("QueueNotExist"))
  36. {
  37. System.out.println("Queue is not exist.Please create before use");
  38. } else if (se.getErrorCode().equals("TimeExpired"))
  39. {
  40. System.out.println("The request is time expired. Please check your local machine timeclock");
  41. }
  42. /*
  43. you can get more MNS service error code from following link:
  44. https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html
  45. */
  46. }
  47. } catch (Exception e)
  48. {
  49. System.out.println("Unknown exception happened!");
  50. e.printStackTrace();
  51. }
  52. client.close();
  53. }
  54. }

最後更新:2016-08-18 13:23:34

  上一篇:go 發送消息示例代碼__Java SDK_SDK使用手冊_消息服務-阿裏雲
  下一篇:go 並發測試示例代碼__Java SDK_SDK使用手冊_消息服務-阿裏雲