我正在尝试处理生产者和消费者的简单RabbitMQ实例。
public void newCustomerToQueue(Custom custom) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
CustomWrap custom= new CustomWrap();
custom.setname(custom.getname());
String jsonString;
try {
jsonString = new ObjectMapper().writeValueAsString(custom);
// System.out.println(jsonString);
} catch (IOException e) {
throw new RuntimeException(e); //todo
}
try {
channel.basicPublish("",TASK_QUEUE_NAME, null, SerializationUtils.serialize(jsonString));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" [x] Sent '" + jsonString + "'");
}
我的接班人如下:
public void ReceiveLead() throws Exception{
final String TASK_QUEUE_NAME = "task_queue";
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
final com.rabbitmq.client.Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
channel.basicQos(1);
final Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println("Recieved" +message);
try {
byte[] body1 = message.getBytes();
System.out.println("inside"+new String(body1));
doWork(body1);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println(" [x] Done");
channel.basicAck(envelope.getDeliveryTag(), false);
}
}
};
channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
}
问题是当我收到此特定消息时,我的字符串中将附加字符,例如: 收到了'?? t = {“名称”:“字符串”}' 有人可以帮帮我吗,我似乎找不到原因了!
答案 0 :(得分:0)
带有有效负载的字符串应使用UTF-8编码转换为字节数组:
jsonString.getBytes(Charset.forName("UTF-8"));
在这种情况下,不应使用SerializationUtils.serialize
,因为它会添加有关序列化对象的其他元数据。