在使用Python 搭建gprc框架時,遇到傳輸文件大小限制,異常信息如下:
Traceback (most recent call last):
File "/grpc_demo/demo_client.py", line 47, in <module>
run("localhost:18991", ".")
File "/grpc_demo/demo_client.py", line 29, in run
response = stub.CreateFile(demo_pb2.FileRequest(file=data, name='ffile.jpg'.encode('utf-8'), rpath=rpath.encode('utf-8')))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.RESOURCE_EXHAUSTED
details = "Received message larger than max (5009675 vs. 4194304)"
debug_error_string = "{"created":"@1593481044.082878000","description":"Error received from peer ipv6:[::1]:18991","file":"src/core/lib/surface/call.cc","file_line":1055,"grpc_message":"Received message larger than max (5009675 vs. 4194304)","grpc_status":8}"
>
這是因爲grpc默認傳輸文件大小爲4*1024*1024 也就是4兆,超出此大小便會拋出StatusCode.RESOURCE_EXHAUSTED這個異常,解決此問題需要修改默認傳輸大小限制。查閱各種資料,發現大多爲golang版本的解決方案,經過摸索測試,發現如下解決方案:
在server創建時添加options參數:
MAX_MESSAGE_LENGTH = 256*1024*1024 # 可根據具體需求設置,此處設爲256M
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), options=[
('grpc.max_send_message_length', MAX_MESSAGE_LENGTH),
('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH),
]
)
只需將服務端設置便可。