PHP中Protobuf的uint64类型值转负数及解析失败问题咨询
问题描述
定义了如下Protobuf消息:
message Product { uint64 id = 1; uint64 order_id = 2; }
在PHP中构建响应:
(new Product()) ->setId(3) ->setOrderId(3875412541)
得到的结果出现整数溢出:
{ "id": 3, "order_id": -419554755 }
当order_id为11位及以上数字时,直接抛出解析错误:
13 INTERNAL: Failed to parse server response
仅当order_id为8位数字时能正常工作:
{ "id": 3, "order_id": 38754125 }
解决方案
传递字符串形式的大整数:PHP中整数超过
PHP_INT_MAX会自动转为浮点数或溢出,直接给setOrderId传入字符串格式的数字,Protobuf客户端会正确处理uint64类型:(new Product()) ->setId(3) ->setOrderId('3875412541')切换到64位PHP环境:32位PHP的
PHP_INT_MAX仅为2147483647,远小于uint64的最大值(18446744073709551615),64位PHP原生支持更大范围的整数,能从根源减少溢出问题。升级Protobuf PHP库:旧版本的
google/protobuf依赖对uint64大整数处理存在bug,执行以下命令升级到最新版本:composer update google/protobuf配置JSON序列化格式(可选):如果需要JSON输出时保留完整的uint64数字,可在Protobuf消息中添加JSON选项,指定uint64字段序列化为字符串:
import "google/protobuf/descriptor.proto"; message Product { option (google.protobuf.json_format) = { uint64_format: STRING }; uint64 id = 1; uint64 order_id = 2; }序列化后的JSON结果会以字符串形式展示uint64值,避免前端解析溢出:
{ "id": "3", "order_id": "3875412541" }
内容的提问来源于stack exchange,提问作者arakibi
相关产品推荐
相关产品推荐

