RabbitMQ Python端发送消息给Java端 接受消息全数字问题
文章目录RabbitMQ接受一堆数字Bug参考RabbitMQ接受一堆数字BugPython发送端用 pika 发送消息发送代码是这样的:#!/usr/bin/python# -*- coding:utf-8 -*-import pikaimport jsoncredentials = pika.PlainCredentials('ding', 'ding')connectio...
·
文章目录
RabbitMQ接受一堆数字Bug
Python发送端用 pika 发送消息
发送代码是这样的:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import pika
import json
credentials = pika.PlainCredentials('ding', 'ding')
connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.0.200',5672,'/',credentials))
channel = connection.channel()
channel.queue_declare(queue='test queue')
msg = 'GG next'
channel.basic_publish(exchange='',
routing_key='test queue',
body=msg)
connection.close()
Java接收端是 Spring boot 项目,集成了 RabbitMQ 的包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
接收代码是这样的:
@RabbitListener(queues = "test queue")
public void process2(String message) {
System.out.println(message);
}
运行Python脚本,Java端得到的结果是这样的:
71,71,32,110,101,120,116
结果全是 ASCII码了!之前用Java集成了 RabbitMQ,Java和Java之间是没有这个问题的。于是想到在Java端把 ASCII 码转换为字符串,就写了下面的代码:
@RabbitListener(queues = "test queue")
public void process2(String message) {
System.out.println(arrayToStr(ascToArray(message)));
}
private String arrayToStr(int[] arr) {
String res = "";
for (int i = 0; i < arr.length; i++) {
res += Character.toString((char)arr[i]);
}
return res;
}
private int[] ascToArray(String str) {
String[] arr = str.split(",");
int[] resArr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
resArr[i] = Integer.parseInt(arr[i]);
}
return resArr;
}
得到的结果正常了:
GG next
正有点开心之际,想到一个问题,中文字符怎么办?一个汉字两个字节,ASCII码可表示不了啊?
于是试验一下Python端发送
msg = 'GG 下一把'
Java端果然出问题了:
GG ¦ᄌヒ¦ᄌタ₩ハハ
这时我们可以看看 RabbitMQ 给我发送过来的到底是啥,Java端代码变成这样:
@RabbitListener(queues = "test queue")
public void process2(Object message) {
System.out.println(message);
}
Python发送端发来的是这样的:
(Body:'[B@49d1204c(byte[12])' MessageProperties [headers={}, contentLength=0, redelivered=false, receivedExchange=, receivedRoutingKey=test queue, deliveryTag=1, consumerTag=amq.ctag-Q4Oy_yC5qRoLoxAdu50zaw, consumerQueue=test queue])
Java发送端发来的是这样的:
(Body:'GG 下一把' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=queue, deliveryTag=1, consumerTag=amq.ctag-o1v48tbAr8mu-pT7HZHvHA, consumerQueue=queue])
居然一个是 byte[] 数组一个是 String这可怎么办?解决代码如下:
import org.springframework.amqp.core.Message;
@RabbitListener(queues = "test queue")
public void process2(Message message) {
String messageBody = new String(message.getBody());
System.out.println(messageBody);
}
不论是Java端还是Python端发来的,都能正确显示了。
GG 下一把
参考
更多推荐
已为社区贡献2条内容
所有评论(0)