Example #1
0
        public TransportMessage GetTransportMessage(object [] objects)
        {
            var message = new TransportMessage
            {
                ContentType = ContentType,
                Id          = Id,
                Content     = null
            };

            object contentObject;

            if (IsInvokeMessage())
            {
                contentObject =
                    SerializerUtilitys.Deserialize <MessagePackRemoteInvokeMessage>(Content).GetRemoteInvokeMessage();
            }
            else if (IsInvokeResultMessage())
            {
                var resultObj = objects[1] as object[];
                contentObject = new RemoteInvokeResultMessage
                {
                    ExceptionMessage = objects[0] == null ? null : objects[0].ToString(),
                    Result           = resultObj[1].ToString().Substring(1)
                };
            }
            else
            {
                throw new NotSupportedException($"无法支持的消息类型:{ContentType}!");
            }
            message.Content = contentObject;
            return(message);
        }
        private async Task LocalExecuteAsync(ServiceEntity entry, RemoteInvokeMessage remoteInvokeMessage,
                                             RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                var result = await entry.Func(remoteInvokeMessage.Parameters);

                var task = result as Task;

                if (task == null)
                {
                    resultMessage.Result = result;
                }
                else
                {
                    task.Wait();

                    var taskType = task.GetType().GetTypeInfo();
                    if (taskType.IsGenericType)
                    {
                        resultMessage.Result = taskType.GetProperty("Result")?.GetValue(task);
                    }
                }
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError("执行本地逻辑时候发生了错误", exception);
                }
                resultMessage.ExceptionMessage = GetExceptionMessage(exception);
            }
        }
Example #3
0
        private async Task SendRemoteInvokeResult(IMessageSender sender, string messageId,
                                                  RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug("准备发送响应消息。");
                }

                await sender.SendAndFlushAsync(TransportMessage.CreateInvokeResultMessage(messageId, resultMessage));

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug("响应消息发送成功。");
                }
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError(exception, "发送响应消息时候发生了异常。");
                }
            }
        }
Example #4
0
        /// <summary>
        /// 远程调用。
        /// </summary>
        /// <param name="parameters">参数字典。</param>
        /// <param name="serviceId">服务Id。</param>
        /// <returns>调用任务。</returns>
        protected async Task Invoke(IDictionary <string, object> parameters, string serviceId)
        {
            var existsInterceptor             = _interceptors.Any();
            RemoteInvokeResultMessage message = null;

            if (!existsInterceptor)
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, false);
            }
            else
            {
                var invocation = GetInvocation(parameters, serviceId, typeof(Task));
                foreach (var interceptor in _interceptors)
                {
                    var interceptReuslt = await Intercept(interceptor, invocation);

                    message = interceptReuslt.Item1;
                }
            }
            if (message == null || !message.IsSucceedRemoteInvokeCalled())
            {
                var command = await _commandProvider.GetCommand(serviceId);
                await FallBackRetryInvoke(parameters, serviceId, command);
            }
        }
Example #5
0
        private async Task LocalExecuteAsync(ServiceEntity entry, RemoteInvokeMessage remoteInvokeMessage,
                                             RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                var result = await entry.Func(remoteInvokeMessage.Parameters);

                var task = result as Task;

                if (task == null)
                {
                    resultMessage.Result = result;
                }
                else
                {
                    task.Wait();

                    var taskType = task.GetType().GetTypeInfo();
                    if (taskType.IsGenericType)
                    {
                        resultMessage.Result = taskType.GetProperty("Result").GetValue(task);
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                resultMessage.ExceptionMessage = GetExceptionMessage(exception);
            }
        }
 /// <summary>
 /// 创建一个调用结果传输消息。
 /// </summary>
 /// <param name="id">消息Id。</param>
 /// <param name="invokeResultMessage">调用结果实例。</param>
 /// <returns>调用结果传输消息。</returns>
 public static TransportMessage CreateInvokeResultMessage(string id, RemoteInvokeResultMessage invokeResultMessage)
 {
     return(new TransportMessage(invokeResultMessage)
     {
         Id = id
     });
 }
        /// <summary>
        /// 远程调用。
        /// </summary>
        /// <param name="parameters">参数字典。</param>
        /// <param name="serviceId">服务Id。</param>
        /// <returns>调用任务。</returns>
        protected async Task Invoke(IDictionary <string, object> parameters, string serviceId)
        {
            var existsInterceptor             = _interceptors.Any();
            RemoteInvokeResultMessage message = null;

            if (!existsInterceptor)
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, false);
            }
            else
            {
                var invocation = GetInvocation(parameters, serviceId, typeof(Task));
                foreach (var interceptor in _interceptors)
                {
                    var interceptReuslt = await Intercept(interceptor, invocation);

                    message = interceptReuslt.Item1;
                }
            }
            if (message == null)
            {
                var command = await _commandProvider.GetCommand(serviceId);

                if (command.FallBackName != null && _serviceProvider.IsRegistered <IFallbackInvoker>(command.FallBackName) && command.Strategy == StrategyType.FallBack)
                {
                    var invoker = _serviceProvider.GetInstances <IFallbackInvoker>(command.FallBackName);
                    await invoker.Invoke <object>(parameters, serviceId, _serviceKey);
                }
                else
                {
                    var invoker = _serviceProvider.GetInstances <IClusterInvoker>(command.Strategy.ToString());
                    await invoker.Invoke(parameters, serviceId, _serviceKey, true);
                }
            }
        }
Example #8
0
        /// <summary>
        /// 远程调用。
        /// </summary>
        /// <typeparam name="T">返回类型。</typeparam>
        /// <param name="parameters">参数字典。</param>
        /// <param name="serviceId">服务Id。</param>
        /// <returns>调用结果。</returns>
        protected async Task <T> Invoke <T>(IDictionary <string, object> parameters, string serviceId)
        {
            object result  = default(T);
            var    vt      = _commandProvider.GetCommand(serviceId);
            var    command = vt.IsCompletedSuccessfully ? vt.Result : await vt;
            RemoteInvokeResultMessage message = null;
            var         decodeJOject          = typeof(T) == TypeHelper.ObjectType;
            IInvocation invocation            = null;
            var         existsInterceptor     = _interceptors.Any();
            var         serviceRoute          = await _serviceRouteProvider.Locate(serviceId);

            if ((serviceRoute == null || !serviceRoute.ServiceDescriptor.ExistIntercept()) || decodeJOject)
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey,
                                                                       decodeJOject);

                if (message == null)
                {
                    if (command.FallBackName != null &&
                        _serviceProvider.IsRegistered <IFallbackInvoker>(command.FallBackName) &&
                        command.Strategy == StrategyType.FallBack)
                    {
                        var invoker = _serviceProvider.GetInstances <IFallbackInvoker>(command.FallBackName);
                        return(await invoker.Invoke <T>(parameters, serviceId, _serviceKey));
                    }
                    else
                    {
                        var invoker = _serviceProvider.GetInstances <IClusterInvoker>(command.Strategy.ToString());
                        return(await invoker.Invoke <T>(parameters, serviceId, _serviceKey,
                                                        typeof(T) == TypeHelper.ObjectType));
                    }
                }
            }
            else
            {
                invocation = invocation == null?GetInvocation(parameters, serviceId, typeof(T)) : invocation;

                foreach (var interceptor in _interceptors)
                {
                    var interceptReuslt = await Intercept(interceptor, invocation);

                    message = interceptReuslt.Item1;
                    result  = interceptReuslt.Item2 == null ? default(T) : interceptReuslt.Item2;
                }
            }

            if (message != null)
            {
                if (message.Result == null)
                {
                    result = message.Result;
                }
                else
                {
                    result = _typeConvertibleService.Convert(message.Result, typeof(T));
                }
            }

            return((T)result);
        }
Example #9
0
        /// <summary>
        /// 远程调用。
        /// </summary>
        /// <typeparam name="T">返回类型。</typeparam>
        /// <param name="parameters">参数字典。</param>
        /// <param name="serviceId">服务Id。</param>
        /// <returns>调用结果。</returns>
        protected async Task <T> Invoke <T>(IDictionary <string, object> parameters, string serviceId)
        {
            object result  = default(T);
            var    command = await _commandProvider.GetCommand(serviceId);

            RemoteInvokeResultMessage message = null;
            var         decodeJOject          = typeof(T) == UtilityType.ObjectType;
            IInvocation invocation            = null;
            var         existsInterceptor     = _interceptors.Any();

            if ((_cacheInterceptor == null || !command.RequestCacheEnabled) && !existsInterceptor)
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject);

                if (message == null || !message.IsSucceedRemoteInvokeCalled())
                {
                    return(await FallBackRetryInvoke <T>(parameters, serviceId, command));
                }
            }
            if (_cacheInterceptor != null && command.RequestCacheEnabled)
            {
                invocation = GetCacheInvocation(parameters, serviceId, typeof(T));
                if (invocation != null)
                {
                    var interceptReuslt = await Intercept(_cacheInterceptor, invocation);

                    message = interceptReuslt.Item1;
                    result  = interceptReuslt.Item2 == null ? default(T) : interceptReuslt.Item2;
                }
                else
                {
                    message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject);

                    if (message == null || !message.IsSucceedRemoteInvokeCalled())
                    {
                        return(await FallBackRetryInvoke <T>(parameters, serviceId, command));
                    }
                }
            }
            if (existsInterceptor)
            {
                invocation = invocation == null?GetInvocation(parameters, serviceId, typeof(T)) : invocation;

                foreach (var interceptor in _interceptors)
                {
                    var interceptReuslt = await Intercept(interceptor, invocation);

                    message = interceptReuslt.Item1;
                    result  = interceptReuslt.Item2 == null ? default(T) : interceptReuslt.Item2;
                }
            }
            if (message != null)
            {
                result = await GetInvokeResult <T>(message);
            }
            return((T)result);
        }
        /// <summary>
        /// 执行消息转换后的服务
        /// </summary>
        /// <param name="sender">消息发送者</param>
        /// <param name="message">调用消息</param>
        public async Task ExecuteAsync(IMessageSender sender, TransportMessage message)
        {
            if (!message.IsInvokeMessage())
            {
                return;
            }

            RemoteInvokeMessage remoteInvokeMessage;

            try
            {
                remoteInvokeMessage = message.GetContent <RemoteInvokeMessage>();
            }
            catch (Exception exception)
            {
                _logger.LogError("将接收到的消息反序列化成 TransportMessage<RemoteInvokeMessage> 时发送了错误。", exception);
                return;
            }

            // 定位远程调用的消息服务实体
            var entry = _serviceEntryLocate.Locate(remoteInvokeMessage);

            if (entry == null)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError($"根据服务Id:{remoteInvokeMessage.ServiceId},找不到服务条目");
                }
                return;
            }

            _logger.LogInformation("准备执行本地逻辑");
            var resultMessage = new RemoteInvokeResultMessage();

            // 是否需要等待执行
            if (entry.Descriptor.WaitExecution())
            {
                //执行本地代码
                await LocalExecuteAsync(entry, remoteInvokeMessage, resultMessage);

                //向客户端发送调用结果
                await SendRemoteInvokeResult(sender, message.Id, resultMessage);
            }
            else
            {
                //通知客户端已接收到消息
                await SendRemoteInvokeResult(sender, message.Id, resultMessage);

                //确保新起一个线程执行,不堵塞当前线程
                await Task.Factory.StartNew(async() =>
                {
                    //执行本地代码
                    await LocalExecuteAsync(entry, remoteInvokeMessage, resultMessage);
                },
                                            TaskCreationOptions.LongRunning);
            }
        }
        /// <summary>
        /// 远程调用。
        /// </summary>
        /// <typeparam name="T">返回类型。</typeparam>
        /// <param name="parameters">参数字典。</param>
        /// <param name="serviceId">服务Id。</param>
        /// <returns>调用结果。</returns>
        protected async Task <T> Invoke <T>(IDictionary <string, object> parameters, string serviceId)
        {
            object result  = default(T);
            var    command = await _commandProvider.GetCommand(serviceId);

            RemoteInvokeResultMessage message = null;
            var         decodeJOject          = typeof(T) == UtilityType.ObjectType;
            IInvocation invocation            = null;
            var         existsInterceptor     = _interceptors.Any();

            if ((!command.RequestCacheEnabled || decodeJOject) && !existsInterceptor)
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject);

                if (message == null)
                {
                    if (command.FallBackName != null && _serviceProvider.IsRegistered <IFallbackInvoker>(command.FallBackName) && command.Strategy == StrategyType.FallBack)
                    {
                        var invoker = _serviceProvider.GetInstances <IFallbackInvoker>(command.FallBackName);
                        return(await invoker.Invoke <T>(parameters, serviceId, _serviceKey));
                    }
                    else
                    {
                        var invoker = _serviceProvider.GetInstances <IClusterInvoker>(command.Strategy.ToString());
                        return(await invoker.Invoke <T>(parameters, serviceId, _serviceKey, typeof(T) == UtilityType.ObjectType));
                    }
                }
            }
            if (command.RequestCacheEnabled && !decodeJOject)
            {
                invocation = GetCacheInvocation(parameters, serviceId, typeof(T));
                var interceptReuslt = await Intercept(_cacheInterceptor, invocation);

                message = interceptReuslt.Item1;
                result  = interceptReuslt.Item2 == null ? default(T) : interceptReuslt.Item2;
            }
            if (existsInterceptor)
            {
                invocation = invocation == null?GetInvocation(parameters, serviceId, typeof(T)) : invocation;

                foreach (var interceptor in _interceptors)
                {
                    var interceptReuslt = await Intercept(interceptor, invocation);

                    message = interceptReuslt.Item1;
                    result  = interceptReuslt.Item2 == null ? default(T) : interceptReuslt.Item2;
                }
            }
            if (message != null)
            {
                result = _typeConvertibleService.Convert(message.Result, typeof(T));
            }
            return((T)result);
        }
Example #12
0
        public async Task <RemoteInvokeResultMessage> InvokerAsync(TransportMessage message)
        {
            if (!message.IsInvokeMessage())
            {
                return(null);
            }

            RemoteInvokeMessage remoteInvokeContext;

            try
            {
                remoteInvokeContext = message.GetContent <RemoteInvokeMessage>();
            }
            catch (Exception exception)
            {
                _logger.LogError("将接收到的消息反序列化成 TransportMessage<RemoteInvokeMessage> 时发送了错误。", exception);
                return(null);
            }
            var resultMessage = new RemoteInvokeResultMessage();

            try
            {
                var entry  = _entryLocator.Locate(remoteInvokeContext.ServiceId);
                var result = await entry.Func(remoteInvokeContext.Parameters);

                var task = result as Task;

                if (task == null)
                {
                    resultMessage.Result = result;
                }
                else
                {
                    task.Wait();

                    var taskType = task.GetType().GetTypeInfo();
                    if (taskType.IsGenericType)
                    {
                        resultMessage.Result = taskType.GetProperty("Result").GetValue(task);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError("执行本地服务调用发生错误", e);
                resultMessage.ExceptionMessage = GetExceptionMessage(e);
            }
            return(resultMessage);
        }
Example #13
0
        private async Task SendRemoteInvokeResult(IMessageSender sender, string messageId,
                                                  RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                Console.WriteLine("准备发送响应消息");
                await sender.SendAndFlushAsync(TransportMessage.CreateInvokeResultMessage(messageId, resultMessage));

                Console.WriteLine("响应消息发送成功");
            }
            catch (Exception exception)
            {
                Console.WriteLine("发送响应消息时候发生了异常" + exception);
            }
        }
Example #14
0
        private async Task LocalExecuteAsync(ServiceEntry entry, RemoteInvokeMessage remoteInvokeMessage,
                                             RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                var result = await entry.Func(remoteInvokeMessage.ServiceKey, remoteInvokeMessage.Parameters);

                var task = result as Task;

                if (task == null)
                {
                    resultMessage.Result = result;
                }
                else
                {
                    if (!task.IsCompletedSuccessfully)
                    {
                        await task;
                    }

                    var taskType = task.GetType().GetTypeInfo();
                    if (taskType.IsGenericType)
                    {
                        resultMessage.Result = taskType.GetProperty("Result").GetValue(task);
                    }
                }

                if (remoteInvokeMessage.DecodeJObject &&
                    !(resultMessage.Result is IConvertible && TypeHelper.ConvertibleType.GetTypeInfo()
                      .IsAssignableFrom(resultMessage.Result.GetType())))
                {
                    resultMessage.Result = JsonConvert.SerializeObject(resultMessage.Result);
                }
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError(exception, "执行本地逻辑时候发生了错误。");
                }

                resultMessage.ExceptionMessage = GetExceptionMessage(exception);
                resultMessage.StatusCode       = exception.HResult;
            }
        }
        public async Task <object> Invoke(IDictionary <string, object> parameters, Type returnType, string serviceId, string _serviceKey, bool decodeJOject)
        {
            var    time   = 0;
            object result = null;
            RemoteInvokeResultMessage message = null;
            var command = await _commandProvider.GetCommand(serviceId);

            do
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject, true);

                if (message != null)
                {
                    if (message.StatusCode == StatusCode.Success)
                    {
                        if (message.Result != null)
                        {
                            result = _typeConvertibleService.Convert(message.Result, returnType);
                        }
                        else
                        {
                            result = message.Result;
                        }
                    }
                    else if (message.IsFailedRemoteInvokeCalled())
                    {
                        continue;
                    }
                    else if (message.IsSucceedRemoteInvokeCalled())
                    {
                        throw message.GetExceptionByStatusCode();
                    }
                }
            } while ((message == null || !message.IsSucceedRemoteInvokeCalled()) && ++time < command.FailoverCluster);

            if (message == null)
            {
                throw new CPlatformException($"{serviceId}远程服务调用失败,暂不存在可用的服务实例");
            }
            if (message.StatusCode != StatusCode.Success)
            {
                throw message.GetExceptionByStatusCode();
            }
            return(result);
        }
        public async Task <T> Invoke <T>(IDictionary <string, object> parameters, string serviceId, string _serviceKey, bool decodeJOject)
        {
            var time   = 0;
            T   result = default(T);
            RemoteInvokeResultMessage message = null;
            var command = await _commandProvider.GetCommand(serviceId);

            do
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject);

                if (message != null && message.Result != null)
                {
                    result = (T)_typeConvertibleService.Convert(message.Result, typeof(T));
                }
            } while (message == null && ++time < command.FailoverCluster);
            return(result);
        }
        private async Task SendRemoteInvokeResult(IMessageSender sender, string messageId,
                                                  RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                _logger.LogInformation("准备发送响应消息");
                await sender.SendAndFlushAsync(TransportMessage.CreateInvokeResultMessage(messageId, resultMessage));

                _logger.LogInformation("响应消息发送成功");
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError("发送响应消息时候发生了异常。", exception);
                }
            }
        }
Example #18
0
        private Task <T> GetInvokeResult <T>(RemoteInvokeResultMessage message)
        {
            return(Task.Run(() =>
            {
                object result = default(T);
                if (message.StatusCode == StatusCode.Success)
                {
                    if (message.Result != null)
                    {
                        result = _typeConvertibleService.Convert(message.Result, typeof(T));
                    }
                }
                else
                {
                    throw message.GetExceptionByStatusCode();
                }

                return (T)result;
            }));
        }
Example #19
0
        public async Task Invoke(IDictionary <string, object> parameters, string serviceId, string _serviceKey, bool decodeJOject)
        {
            var time    = 0;
            var command = await _commandProvider.GetCommand(serviceId);

            RemoteInvokeResultMessage message = null;

            do
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject);

                if (message != null && message.Result != null)
                {
                    if (message.StatusCode != StatusCode.Success && time >= command.FailoverCluster)
                    {
                        throw new CPlatformException(message.ExceptionMessage, message.StatusCode);
                    }
                }
            }while ((message == null || message.StatusCode == StatusCode.ServiceUnavailability) && ++time < command.FailoverCluster);
        }
Example #20
0
        private async Task OnAuthorization(ServiceEntry entry, RemoteInvokeMessage remoteInvokeMessage,
                                           RemoteInvokeResultMessage resultMessage, CancellationTokenSource cancelTokenSource)
        {
            if (entry.Descriptor.EnableAuthorization() && entry.Descriptor.AuthType() == AuthorizationType.AppSecret.ToString())
            {
                var route = await _serviceRouteProvider.Locate(entry.Descriptor.Id);

                var routeContext = new ServiceRouteContext()
                {
                    Route         = route,
                    InvokeMessage = remoteInvokeMessage,
                    ResultMessage = resultMessage,
                };
                _authorizationFilter.ExecuteAuthorizationFilterAsync(routeContext, cancelTokenSource.Token);
                if (!string.IsNullOrEmpty(resultMessage.ExceptionMessage))
                {
                    cancelTokenSource.Cancel();
                }
            }
        }
Example #21
0
        public async Task <T> Invoke <T>(IDictionary <string, object> parameters, string serviceId, string _serviceKey, bool decodeJOject)
        {
            var time   = 0;
            T   result = default(T);
            RemoteInvokeResultMessage message = null;
            var vtCommand = _commandProvider.GetCommand(serviceId);
            var command   = vtCommand.IsCompletedSuccessfully ? vtCommand.Result : await vtCommand;

            do
            {
                message = await _breakeRemoteInvokeService.InvokeAsync(parameters, serviceId, _serviceKey, decodeJOject);

                if (message != null && message.Result != null)
                {
                    if (message.StatusCode != StatusCode.Success && time >= command.FailoverCluster)
                    {
                        throw new CPlatformException(message.ExceptionMessage, message.StatusCode);
                    }
                    result = (T)_typeConvertibleService.Convert(message.Result, typeof(T));
                }
            } while ((message == null || message.StatusCode == StatusCode.ServiceUnavailability) && ++time < command.FailoverCluster);
            return(result);
        }
Example #22
0
        private Task <object> GetInvokeResult(RemoteInvokeResultMessage message, Type returnType)
        {
            return(Task.Run(() =>
            {
                object result;
                if (message.StatusCode == StatusCode.Success)
                {
                    if (message.Result != null)
                    {
                        result = _typeConvertibleService.Convert(message.Result, returnType);
                    }
                    else
                    {
                        result = message.Result;
                    }
                }
                else
                {
                    throw message.GetExceptionByStatusCode();
                }

                return result;
            }));
        }
 public override async Task Proceed()
 {
     try
     {
         if (_returnValue == null)
         {
             var proceedResult = await(Proxy as ServiceProxyBase).CallInvoke(this);
             _returnValue = proceedResult;
             _remoteInvokeResultMessage = new RemoteInvokeResultMessage()
             {
                 Result = proceedResult,
             };
         }
     }
     catch (Exception ex)
     {
         _returnValue = null;
         _remoteInvokeResultMessage = new RemoteInvokeResultMessage()
         {
             ExceptionMessage = ex.GetExceptionMessage(),
             StatusCode       = ex.GetExceptionStatusCode()
         };
     }
 }
 public ProtoBufferRemoteInvokeResultMessage(RemoteInvokeResultMessage message)
 {
     ExceptionMessage = message.ExceptionMessage;
     Result           = message.Result == null ? null : new ProtoBufferDynamicItem(message.Result);
 }
Example #25
0
        private async Task LocalExecuteAsync(ServiceEntry entry, RemoteInvokeMessage remoteInvokeMessage, RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                var result = await entry.Func(remoteInvokeMessage.Parameters);

                resultMessage.Result = result;
                //if (result.GetType() == typeof(Task))
                //{
                //    resultMessage.Result = null;
                //}
                //else
                //{
                //    var task = result as Task<ActionResult>;
                //    resultMessage.Result  = await task;
                //}
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError("执行本地逻辑时候发生了错误。", exception);
                }
                resultMessage.ExceptionMessage = GetExceptionMessage(exception);
            }
        }
 public MessagePackRemoteInvokeResultMessage(RemoteInvokeResultMessage message)
 {
     ExceptionMessage = message.ExceptionMessage;
     Result           = message.Result == null ? null : new DynamicItem(message.Result);
 }
Example #27
0
        private async Task LocalExecuteAsync(ServiceEntry entry, RemoteInvokeMessage remoteInvokeMessage, RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                var cancelTokenSource = new CancellationTokenSource();
                await OnAuthorization(entry, remoteInvokeMessage, resultMessage, cancelTokenSource);

                if (!cancelTokenSource.IsCancellationRequested)
                {
                    var result = await entry.Func(remoteInvokeMessage.ServiceKey, remoteInvokeMessage.Parameters);

                    var task = result as Task;

                    if (task == null)
                    {
                        resultMessage.Result = result;
                    }
                    else
                    {
                        task.Wait();
                        var taskType = task.GetType().GetTypeInfo();
                        if (taskType.IsGenericType)
                        {
                            resultMessage.Result = taskType.GetProperty("Result").GetValue(task);
                        }
                    }
                    if (remoteInvokeMessage.DecodeJOject && !(resultMessage.Result is IConvertible && typeof(IConvertible).GetTypeInfo().IsAssignableFrom(resultMessage.Result.GetType())))
                    {
                        resultMessage.Result = JsonConvert.SerializeObject(resultMessage.Result);
                    }
                }
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError("执行本地逻辑时候发生了错误。", exception);
                }
                resultMessage.ExceptionMessage = GetExceptionMessage(exception);
            }
        }
Example #28
0
        /// <summary>
        /// 执行。
        /// </summary>
        /// <param name="sender">消息发送者。</param>
        /// <param name="message">调用消息。</param>
        public async Task ExecuteAsync(IMessageSender sender, TransportMessage message)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("接收到消息。");
            }

            if (!message.IsInvokeMessage())
            {
                return;
            }

            RemoteInvokeMessage remoteInvokeMessage;

            try
            {
                remoteInvokeMessage = message.GetContent <RemoteInvokeMessage>();
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "将接收到的消息反序列化成 TransportMessage<RemoteInvokeMessage> 时发送了错误。");
                return;
            }

            var entry = _serviceEntryLocate.Locate(remoteInvokeMessage);

            if (entry == null)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError($"根据服务Id:{remoteInvokeMessage.ServiceId},找不到服务条目。");
                }
                return;
            }

            if (remoteInvokeMessage.Attachments != null)
            {
                foreach (var attachment in remoteInvokeMessage.Attachments)
                {
                    RpcContext.GetContext().SetAttachment(attachment.Key, attachment.Value);
                }
            }


            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("准备执行本地逻辑。");
            }

            var resultMessage = new RemoteInvokeResultMessage();

            //是否需要等待执行。
            if (entry.Descriptor.WaitExecution())
            {
                //执行本地代码。
                await  LocalExecuteAsync(entry, remoteInvokeMessage, resultMessage);

                //向客户端发送调用结果。
                await SendRemoteInvokeResult(sender, message.Id, resultMessage);
            }
            else
            {
                //通知客户端已接收到消息。
                await SendRemoteInvokeResult(sender, message.Id, resultMessage);

                //确保新起一个线程执行,不堵塞当前线程。
                await Task.Factory.StartNew(async() =>
                {
                    //执行本地代码。
                    await LocalExecuteAsync(entry, remoteInvokeMessage, resultMessage);
                }, TaskCreationOptions.LongRunning);
            }
        }
Example #29
0
        /// <summary>
        /// 执行。
        /// </summary>
        /// <param name="sender">消息发送者。</param>
        /// <param name="message">调用消息。</param>
        public async Task ExecuteAsync(IMessageSender sender, TransportMessage message)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.Information("接收到消息。");
            }

            if (!message.IsInvokeMessage())
            {
                return;
            }

            RemoteInvokeMessage remoteInvokeMessage;

            try
            {
                remoteInvokeMessage = _objecSerializer.Deserialize <object, RemoteInvokeMessage>(message.Content);
            }
            catch (Exception exception)
            {
                _logger.Error($"将接收到的消息反序列化成 TransportMessage<RemoteInvokeMessage> 时发送了错误。", exception);
                return;
            }

            var entry = _serviceEntryLocate.Locate(remoteInvokeMessage);

            if (entry == null)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.Error($"根据服务Id:{remoteInvokeMessage.ServiceId},找不到服务条目。");
                }
                return;
            }

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.Debug("准备执行本地逻辑。");
            }

            var resultMessage = new RemoteInvokeResultMessage();

            try
            {
                var result = entry.Func(remoteInvokeMessage.Parameters);
                var task   = result as Task;

                if (task == null)
                {
                    resultMessage.Result = result;
                }
                else
                {
                    task.Wait();

                    var taskType = task.GetType();
                    if (taskType.IsGenericType)
                    {
                        resultMessage.Result = taskType.GetProperty("Result").GetValue(task);
                    }
                }
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.Error("执行本地逻辑时候发生了错误。", exception);
                }
                resultMessage.ExceptionMessage = GetExceptionMessage(exception);
            }

            try
            {
                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.Debug("准备发送响应消息。");
                }

                await sender.SendAsync(TransportMessage.CreateInvokeResultMessage(message.Id, resultMessage));

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.Debug("响应消息发送成功。");
                }
            }
            catch (Exception exception)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.Error("发送响应消息时候发生了异常。", exception);
                }
            }
        }
        private async Task LocalExecuteAsync(ServiceEntry entry, RemoteInvokeMessage remoteInvokeMessage, RemoteInvokeResultMessage resultMessage)
        {
            try
            {
                var result = await entry.Func(remoteInvokeMessage.Parameters);

                if (!(result is Task task))
                {
                    resultMessage.Result = result;
                }
                else
                {
                    task.Wait();

                    var taskType = task.GetType().GetTypeInfo();
                    if (taskType.IsGenericType)
                    {
                        resultMessage.Result = taskType.GetProperty("Result").GetValue(task);
                    }
                }
            }