在Beam Java管道中获取PubSubLite消息属性的问题
解决Beam Java中PubSubLite SequencedMessage属性提取问题
直接通过AttributeValues的类型判断方法提取对应值即可,因为PubSubLite的属性支持多种类型(字符串、整数、布尔、字节数组等),Java库返回的AttributeValues是Protobuf的oneof封装类型,需要显式判断类型后获取底层值:
- 先获取
AttributeValues对象:
AttributeValues attrValue = message.getMessage().getAttributesMap().get("attrKey");
- 根据属性实际类型提取值,以字符串类型为例:
if (attrValue != null && attrValue.hasStringValue()) { String attrStrValue = attrValue.getStringValue(); // 这里就拿到了字符串格式的属性值 }
- 如果属性是其他类型,对应调用不同的getter方法:
- 整数类型:
attrValue.getInt64Value()(需先判断attrValue.hasInt64Value()) - 布尔类型:
attrValue.getBoolValue()(需先判断attrValue.hasBoolValue()) - 字节数组类型:
attrValue.getBytesValue().toByteArray()(需先判断attrValue.hasBytesValue())
- 整数类型:
如果能确定属性的类型,也可以直接调用对应getter,但加上非空和类型判断能避免运行时异常。
内容的提问来源于stack exchange,提问作者psykidellic
相关产品推荐
相关产品推荐

