在Java azure中,打印输出导致while循环输出不同的结果


Printout results in while loop output different results in Java azure

我在java中成功发送json对象到azure云。但问题是我的接收器,消息收到很好,但问题是,当我想把它发送回PHP:我正在发送这个消息:

{" Id ": " 914897 ", "名称":"破窗理论"、"描述":"窗口破"、"PriorityId":"1"}

当我收到这条消息时,我想首先打印出消息以验证我是否得到了结果并发送了它。然而,在while循环中打印正确,但在错误的结果之外,这是我的代码:

 try {
        Configuration config
                = ServiceBusConfiguration.configureWithSASAuthentication(
                );

        ServiceBusContract service = ServiceBusService.create(config);
        ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
        opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
        //send object
        HttpClient httpClient = new DefaultHttpClient();
        Gson gson= new Gson();
        while (true) {
            ReceiveQueueMessageResult resultQM = service.receiveQueueMessage("mobile",opts);
            BrokeredMessage message = resultQM.getValue();
            if (message != null && message.getMessageId() != null) {
                System.out.println("MessageID: " + message.getMessageId());
                // Display the queue message.
                System.out.print("From queue:");
                byte[] b = new byte[20000000];
                String message_from_queue = null;
                String thu =null;
                String jsonn = null;
                int numRead = message.getBody().read(b);

                while (-1 != numRead) {
                    message_from_queue = new String(b);
                   message_from_queue  = message_from_queue .trim();                      
                   numRead = message.getBody().read(b);
                //System.out.print("inside while" +message_from_queue + **"'n");//{"Id":"914897","Name":"Broken window","Description":"Window broken","PriorityId":"1"}**

                                 try {

    HttpPost request = new HttpPost("http://localhost:3308/emlive/index.php/Api/createDefect");
    StringEntity params =new StringEntity("defect=" + message_from_queue );
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.addHeader("Accept","application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
    //System.out.printf("---------------------------------Done-------------------------------");
    // handle response here...
    message.setSessionId("");
    System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
   org.apache.http.util.EntityUtils.consume(response.getEntity());
}
catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}
  }
                  //System.out.print("outside while" +message_from_queue +                   "'n");//Broken window","Description":"Window broken","PriorityId":"1"}                                                            
                System.out.println();
                System.out.println("Custom Property: "
                        + message.getProperty("MyProperty"));
                //service.deleteMessage(message);
                System.out.println("Deleting this message.");
                //service.deleteMessage(message);
            } else {
                System.out.println("Finishing up - no more messages.");
                break;
                // Added to handle no more messages.
                // Could instead wait for more messages to be added.
            }
        }
    } catch (ServiceException e) {
        System.out.print("ServiceException encountered: ");
        System.out.println(e.getMessage());
        System.exit(-1);
    } catch (Exception e) {
        System.out.print("Generic exception encountered: ");
        System.out.println(e.getMessage());
        System.exit(-1);
    }

我得到这样的结果:打印内部while循环:

 while (-1 != numRead) {
 message_from_queue = new String(b);
  message_from_queue  = message_from_queue .trim();                      
  numRead = message.getBody().read(b);
 System.out.print("inside while" +message_from_queue + **"'n");//{"Id":"914897","Name":"Broken window","Description":"Window broken","PriorityId":"1"}**
}

while循环外打印:

System.out.print("outside while" +message_from_queue + "'n");/*Broken window","Description":"Window broken","PriorityId":"1"} 

感谢Dominic Betts从这个链接https://azure.microsoft.com/en-us/documentation/articles/service-bus-java-how-to-use-queues/#comments

我使用了下面的代码来实现我的目标:

 StringBuilder stringBuilder = new StringBuilder();
 stringBuilder.append(message_from_queue );

我认为这个问题是由在内部while循环中做POST请求引起的。内部while循环中的代码用于从队列中读取消息,因此HttpClient的POST请求应该在外部while循环中。

我参考了文档https://azure.microsoft.com/en-us/documentation/articles/service-bus-java-how-to-use-queues/并修改了您的代码如下:

try {
    Configuration config = ServiceBusConfiguration.configureWithSASAuthentication("<namespace>", "<sas_key_name>",
            "<sas_key>", ".servicebus.windows.net");
    ServiceBusContract service = ServiceBusService.create(config);
    ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
    opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
    // send object
    // HttpClient httpClient = new DefaultHttpClient();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // Gson gson = new Gson();
    while (true) {
        ReceiveQueueMessageResult resultQM = service.receiveQueueMessage("mobile", opts);
        BrokeredMessage message = resultQM.getValue();
        if (message != null && message.getMessageId() != null) {
            System.out.println("MessageID: " + message.getMessageId());
            // Display the queue message.
            System.out.print("From queue:");
            byte[] b = new byte[20000000];
            String message_from_queue = null;
            // String thu = null;
            // String jsonn = null;
            int numRead = message.getBody().read(b);
            while (-1 != numRead) {
                message_from_queue = new String(b);
                message_from_queue = message_from_queue.trim();
                numRead = message.getBody().read(b);
                // System.out.print("inside while" +message_from_queue +
                // **"'n");//{"Id":"914897","Name":"Broken
                // window","Description":"Window
                // broken","PriorityId":"1"}**
            }
            // System.out.print("outside while" +message_from_queue +
            // "'n");//Broken window","Description":"Window
            // broken","PriorityId":"1"}
            int statusCode = -1;
            try {
                HttpPost request = new HttpPost("http://localhost:3308/emlive/index.php/Api/createDefect");
                StringEntity params = new StringEntity("defect=" + message_from_queue);
                request.addHeader("content-type", "application/x-www-form-urlencoded");
                request.addHeader("Accept", "application/json");
                request.setEntity(params);
                HttpResponse response = httpClient.execute(request);
                // System.out.printf("---------------------------------Done-------------------------------");
                // handle response here...
                message.setSessionId("");
                System.out.println(EntityUtils.toString(response.getEntity()));
                EntityUtils.consume(response.getEntity());
            } catch (Exception ex) {
                // handle exception here
            } finally {
                httpClient.close();
            }
            System.out.println();
            System.out.println("Custom Property: " + message.getProperty("MyProperty"));
            if (statusCode == 200) {
                // Remove message from queue.
                System.out.println("Deleting this message.");
                service.deleteMessage(message);
            }
        } else {
            System.out.println("Finishing up - no more messages.");
            break;
            // Added to handle no more messages.
            // Could instead wait for more messages to be added.
        }
    }
} catch (ServiceException e) {
    System.out.print("ServiceException encountered: ");
    System.out.println(e.getMessage());
    System.exit(-1);
} catch (Exception e) {
    System.out.print("Generic exception encountered: ");
    System.out.println(e.getMessage());
    System.exit(-1);
}