RabbitMQ for Java: how to send multiple float values?

最后都变了- 提交于 2020-01-17 08:42:27

问题


New to RabbitMQ and message passing APIs. I want to send a triplet of float values every few milliseconds. To initialize my connection/channel, I have:

connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);

Then when I want to send a message, the following does strings:

private void sendMessage(String message) throws IOException {
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
}

How can I change sendMessage to send float x1, float x2, float x3 ?

And on the server-side, how would I receive/parse this message into 3 floats?


回答1:


You can, for instance, use a ByteBuffer:

final ByteBuffer buf = ByteBuffer.allocate(12)  // 3 floats
    .putFloat(f1).putFloat(f2).putFloat(f3);    // put them; .put*() return this
channel.basicPublish(buf.array());              // send

This will write the floats in big endian (default network order and what Java uses as well).

On the receiving side, you would do:

// delivery is a QueuingConsumer.Delivery
final ByteBuffer buf = ByteBuffer.wrap(delivery.getBody());
final float f1 = buf.getFloat();
final float f2 = buf.getFloat();
final float f3 = buf.getFloat();


来源:https://stackoverflow.com/questions/17600563/rabbitmq-for-java-how-to-send-multiple-float-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!