我目前正在使用springAMQP在java和我的RabbitMQ节点之间进行通信。 我正在发送Protobuf数据。
我想将收到的消息转换/转换/解析到相应的ProtoClass中。
以下是我的转换器的代码段:
@Override
protected Message createMessage(Object object, MessageProperties messageProperties) {
Preconditions.checkNotNull(object, "Object to send is null !");
if (!com.google.protobuf.Message.class.isAssignableFrom(object.getClass())) {
throw new MessageConversionException("Message wasn't a protobuf");
} else {
com.google.protobuf.Message protobuf = (com.google.protobuf.Message) object;
byte[] byteArray = protobuf.toByteArray();
messageProperties.setContentLength(byteArray.length);
messageProperties.setContentType(ProtobufMessageConverter.CONTENT_TYPE_PROTOBUF);
messageProperties.setHeader(ProtobufMessageConverter.MESSAGE_TYPE_NAME, protobuf.getDescriptorForType().getName());
return new Message(byteArray, messageProperties);
}
}
@Override
public Object fromMessage(Message message) throws MessageConversionException {
com.google.protobuf.Message parsedMessage = null;
try {
if(ProtobufMessageConverter.CONTENT_TYPE_PROTOBUF.equals(message.getMessageProperties().getContentType())) {
String typeName = getMessageTypeName(message);
Descriptors.Descriptor messageType = fileDescriptor.findMessageTypeByName(typeName);
parsedMessage = DynamicMessage.parseFrom(messageType, message.getBody());
}
} catch (Exception e) {
throw new AmqpRejectAndDontRequeueException("Cannot convert, unknown message type %s".format(getMessageTypeName(message)));
}
return parsedMessage;
}
我需要做些什么才能构建对象?
这是我的原型文件:
message queueReply {
required string identifier = 1; cycle
required uint32 keyId = 2;
required bool success = 3;
required bytes result = 4;
}
我想从template.receiveAndConvert()获取类queueReply
答案 0 :(得分:3)
找到了解决方案。
DynamicMessage o = (DynamicMessage)template.receiveAndConvert("queueName");
ProtoObject request = ProtoObject.parseFrom(o.toByteArray());