1

I have 2 services communicating via AMQP. One uses Javascript with amqplib to send a messageObject {"message":"Success"} like this:

channel.sendToQueue(queueName, Buffer.from(JSON.stringify(messageObject)));

The Java Service consumes the message using spring rabbit like this:

  @RabbitListener(queues = QUEUE_NAME)
  public void receiveMessageQueue(String message) {

the content of that message is string representing an array of bytes. I tried to convert it using the answer posted here It works for 95% of the message But my result still contains some unintelligble characters. Seems like it cannot translate the { and }

\u0017 "message":"Success" \f

So I am wondering, should I change something on the sender side or the receiver side. I'd much rather change the sender side since I have a lot of Java services that expect a ready to use JSON String to be parsed into objects and I don't want to have to update all of them and convert the messages.

EDIT This SO post as mentioned by SMA did not help. Resulting String is exactly the same as the input:

"123,34,106,111,98,73,100,34,58,34,52,54,99,51,101,100,53,54,45,49,101,52,99,45,52,101,49,101,45,97,56,55,55,45,50,55,100,54,53,102,56,50,55,48,51,48,34,44,34,109,101,115,115,97,103,101,34,58,34,83,117,99,99,101,115,115,102,117,108,108,121,32,115,117,98,109,105,116,116,101,100,32,116,111,32,112,46,118,100,115,105,116,116,64,100,105,97,108,111,103,119,111,114,107,115,46,100,101,34,125"

All I can do right now is:

private String convert(String byteString) {
    String[] byteValues = byteString.substring(1, byteString.length() - 1).split(",");
    byte[] bytes = new byte[byteValues.length];
    for (int i=0, len=bytes.length; i<len; i++) {
      bytes[i] = Byte.parseByte(byteValues[i].trim());
    }
    return new String(bytes).replace('\u0017','{').replace('\f','}');
  }

but that seems too hackish. It feels like there should be an easy solition to communicte a JSON string between javascript and java using amqp.

SOLUTION

I found a way to send the message in a way that spring rabbit will understand:

channel.sendToQueue(queueName, Buffer.from(JSON.stringify(messageObject),'utf8'), {contentType:'text/plain', contentEncoding: 'UTF-8'});

Appearently the properties contentType and contentEncoding are a convention, used by the Spring Rabbit message consumer. Now the Java service gets the correct JSON string.

Pete
  • 10,720
  • 25
  • 94
  • 139
  • can you please try the answer on https://stackoverflow.com/questions/17354891/java-bytebuffer-to-string to convert your byte buffer into a String (The default Buffer.from encoding is UTF-8) Please update and see if that worked for you. – JCompetence Feb 17 '22 at 14:59
  • Thanks for the idea. Didn't help though. I added the String I receive on the Java End – Pete Feb 18 '22 at 05:07
  • Great that you resolved it. – JCompetence Feb 18 '22 at 07:25

0 Answers0