public static Task SerializeUnaryResult <T>(UnaryResult <T> result, ServiceContext context) { if (result.hasRawValue) { var bytes = LZ4MessagePackSerializer.Serialize <T>(result.rawValue, context.FormatterResolver); context.Result = bytes; } return(Task.CompletedTask); }
public static async ValueTask SerializeUnaryResult <T>(UnaryResult <T> result, ServiceContext context) { if (result.hasRawValue && !context.IsIgnoreSerialization) { var value = (result.rawTaskValue != null) ? await result.rawTaskValue.ConfigureAwait(false) : result.rawValue; var bytes = LZ4MessagePackSerializer.Serialize <T>(value, context.FormatterResolver); context.Result = bytes; } }
public static T GetResultSync <T>(this UnaryResult <T> resultAsync) { return(resultAsync.ResponseAsync.ConfigureAwait(true).GetAwaiter().GetResult()); }
/// <summary> /// 调用服务方法 /// </summary> /// <returns></returns> protected override async Task <bool> CallMethod() { object result = null; UnaryResult resultType = UnaryResult.Success; ApiResponseType responseType = ApiResponseType.Success; string error = null; // 输出耗时 Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); try { var mi = _invoker.Api.Method; if (mi.ReturnType == typeof(Task)) { // 异步无返回值时 var task = (Task)mi.Invoke(_tgt, _invoker.Args); task.Wait(_invoker.Context.RequestAborted); } else if (typeof(Task).IsAssignableFrom(mi.ReturnType)) { // 异步有返回值 var task = (Task)mi.Invoke(_tgt, _invoker.Args); task.Wait(_invoker.Context.RequestAborted); result = task.GetType().GetProperty("Result").GetValue(task); } else { // 调用同步方法 result = mi.Invoke(_tgt, _invoker.Args); } } catch (Exception ex) { if (ex is OperationCanceledException || ex.InnerException is OperationCanceledException) { // 客户端取消请求,不记录日志,不Response resultType = UnaryResult.Cancel; } else { resultType = UnaryResult.Error; KnownException rpcEx = ex.InnerException as KnownException; if (rpcEx == null) { rpcEx = ex as KnownException; } if (rpcEx != null) { // 业务异常,在客户端作为提示消息,不记日志 responseType = ApiResponseType.Warning; error = rpcEx.Message; } else { // 程序执行过程的错误,将异常记录日志 responseType = ApiResponseType.Error; error = $"调用{_invoker.ApiName}出错"; if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message)) { _invoker.Log.Error(ex.InnerException, error); error += "\r\n" + ex.InnerException.Message; } else { _invoker.Log.Error(ex, error); error += "\r\n" + ex.Message; } } } } finally { stopwatch.Stop(); } if (resultType != UnaryResult.Cancel) { if (TraceRpc) { _invoker.Log.Information("{0} — {1}ms", _invoker.ApiName, stopwatch.ElapsedMilliseconds); } await _invoker.Response(responseType, stopwatch.ElapsedMilliseconds, error == null?result : error); } return(resultType == UnaryResult.Success); }