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

发送消息示例代码

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

发送消息

  1. public class ProducerDemo {
  2. public static void main(String[] args) {
  3. CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
  4. //这个client仅初始化一次
  5. MNSClient client = account.getMNSClient();
  6. //循环发送10条消息
  7. try{
  8. //TestQueue是你的测试队列,请提前创建
  9. CloudQueue queue = client.getQueueRef("TestQueue");
  10. for (int i = 0; i < 10; i++)
  11. {
  12. Message message = new Message();
  13. message.setMessageBody("I am test message " + i);
  14. message.setPriority(8);
  15. Message putMsg = queue.putMessage(message);
  16. System.out.println("Send message id is: " + putMsg.getMessageId());
  17. }
  18. } catch (ClientException ce)
  19. {
  20. System.out.println("Something wrong with the network connection between client and MNS service."
  21. + "Please check your network and DNS availablity.");
  22. ce.printStackTrace();
  23. } catch (ServiceException se)
  24. {
  25. se.printStackTrace();
  26. logger.error("MNS exception requestId:" + se.getRequestId(), se);
  27. if (se.getErrorCode() != null) {
  28. if (se.getErrorCode().equals("QueueNotExist"))
  29. {
  30. System.out.println("Queue is not exist.Please create before use");
  31. } else if (se.getErrorCode().equals("TimeExpired"))
  32. {
  33. System.out.println("The request is time expired. Please check your local machine timeclock");
  34. }
  35. /*
  36. you can get more MNS service error code from following link:
  37. https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html
  38. */
  39. }
  40. } catch (Exception e)
  41. {
  42. System.out.println("Unknown exception happened!");
  43. e.printStackTrace();
  44. }
  45. client.close();
  46. }
  47. }
本文导读目录