全部产品
存储与CDN 数据库 安全 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网 钉钉智能硬件
消息服务

消费消息示例代码

更新时间:2017-11-30 20:50:47

消费消息

  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. // 默认会做 base64 解码
  15. System.out.println("message body: " + popMsg.getMessageBodyAsString());
  16. // 消息 body 的原始数据,不做 base64 解码
  17. // System.out.println("message body: " + popMsg.getMessageBodyAsRawString ());
  18. System.out.println("message id: " + popMsg.getMessageId());
  19. System.out.println("message dequeue count:" + popMsg.getDequeueCount());
  20. //删除已经消费的消息
  21. queue.deleteMessage(popMsg.getReceiptHandle());
  22. System.out.println("delete message successfully.\n");
  23. }
  24. else{
  25. System.out.println("message not exist in TestQueue.\n");
  26. }
  27. }
  28. } catch (ClientException ce)
  29. {
  30. System.out.println("Something wrong with the network connection between client and MNS service."
  31. + "Please check your network and DNS availablity.");
  32. ce.printStackTrace();
  33. } catch (ServiceException se)
  34. {
  35. se.printStackTrace();
  36. logger.error("MNS exception requestId:" + se.getRequestId(), se);
  37. if (se.getErrorCode() != null) {
  38. if (se.getErrorCode().equals("QueueNotExist"))
  39. {
  40. System.out.println("Queue is not exist.Please create before use");
  41. } else if (se.getErrorCode().equals("TimeExpired"))
  42. {
  43. System.out.println("The request is time expired. Please check your local machine timeclock");
  44. }
  45. /*
  46. you can get more MNS service error code from following link:
  47. https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html
  48. */
  49. }
  50. } catch (Exception e)
  51. {
  52. System.out.println("Unknown exception happened!");
  53. e.printStackTrace();
  54. }
  55. client.close();
  56. }
  57. }
本文导读目录