全部产品
存储与CDN 数据库 安全 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 阿里云办公 培训与认证 物联网
消息服务

消费消息示例代码

更新时间:2017-06-07 13:26:11   分享:   

消费消息

  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. }
本文导读目录
本文导读目录
以上内容是否对您有帮助?