解决C#中使用grpc出现Received message larger than max (4427410 vs. 4194304)错误

解决C#中使用grpc出现Received message larger than max (4427410 vs. 4194304)错误

402发表于2019-06-11

今天解决了一个grpc的报错问题。之前用gRPC写了一个批量上传文件的程序,就出现过这个问题。由于当时没有找到好的办法所以临时处理了一下,把每次批量数量改小,很长一段时间没有复现这个问题,但是我知道,这个始终是一下隐患。果不其然,墨菲定理证实了。问题又出现了:

StatusCode=ResourceExhausted, Detail="Received message larger than max (4427410 vs. 4194304)"), Exception=>   在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 Grpc.Core.Internal.AsyncCall`2.UnaryCall(TRequest msg)
   在 Grpc.Core.Calls.BlockingUnaryCall[TRequest,TResponse](CallInvocationDetails`2 call, TRequest req)
   在 Grpc.Core.DefaultCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   在 Grpc.Core.Interceptors.InterceptingCallInvoker.<BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext`2 ctx)
   在 Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext`2 context, BlockingUnaryCallContinuation`2 continuation)
   在 Grpc.Core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)

解决方案:

增大gRPC发送消息和接收消息的大小。因为当调用时超过了gRPC默认值就会报错。

var ip = ConfigurationManager.AppSettings["BindIP"];
var port = int.Parse(ConfigurationManager.AppSettings["BindPort"]);
var options = new List<ChannelOption>();
options.Add(new ChannelOption(ChannelOptions.MaxReceiveMessageLength, Int32.MaxValue));
options.Add(new ChannelOption(ChannelOptions.MaxSendMessageLength, Int32.MaxValue));

Server server = new Server(options)
{
Services = { ScreenshotsService.BindService(new gRPCFileSaveServiceImpl()) },
Ports = { new ServerPort(ip, port, ServerCredentials.Insecure) }
};
server.Start();
from clipboard

小编蓝狐