internal ServiceResponseMessageWithResponseContext triggerRemoteCommand(ServiceUniqueNameInfo serviceName, string requestMessageContent) { var remoteCommandDispatcher = this.createRemoteDispatcher(); var resultWithContext = remoteCommandDispatcher.DispatchCommand(serviceName, requestMessageContent); return(resultWithContext); }
/// <summary> /// 远程服务发现 /// (该方法不会发起远程调用) /// </summary> /// <param name="serviceName">服务名</param> /// <returns>返回服务请求上下文信息列表</returns> public IList <IRpcMessageSenderContext> DiscoverRemoteService(ServiceUniqueNameInfo serviceName) { if (serviceName == null) { throw new ArgumentNullException("serviceName"); } //TODO: 考虑RpcServer的优先级(路由) List <IRpcMessageSenderContext> contextFullList = new List <IRpcMessageSenderContext>(); foreach (IRpcServer rpcServer in this.rpcServers) { //只从启动的RPC服务中查找服务信息 if (rpcServer.Configuration.IsServerStart) { //根据服务名,获取与目标容器通信的RpcServer var contextList = rpcServer.ContextBuilder.BuildSenderContext(serviceName); if (contextList != null && contextList.Count > 0) { contextFullList.AddRange(contextList); } } } return(contextFullList); }
private void Kernel_ComponentRegistered(string key, IHandler handler) { Type targetServiceType = handler.ComponentModel.Implementation; //注册命令服务 if (!typeof(IServiceCommandHandler).IsAssignableFrom(targetServiceType)) { return; } //对于一个服务类,可能实现了多个IServiceCommandHandler, 用以处理多种命令 var interfaces = targetServiceType.GetInterfaces(); foreach (var @interface in interfaces) { if (!typeof(IServiceCommandHandler).IsAssignableFrom(@interface)) { continue; } var genericArgs = @interface.GetGenericArguments(); //IServiceCommandHandler<TCommand, TCommandResult> if (genericArgs.Length == 2) { Type commandType = genericArgs[0]; Type commandResultType = genericArgs[1]; var serviceCommandName = new ServiceUniqueNameInfo(commandType); //验证IServiceCommandHandler只能在对应的服务程序集模块中实现 Assembly shouldBeAssembly; if (!this.serviceAssemblyDic.TryGetValue(serviceCommandName.ServiceAssemblyName, out shouldBeAssembly)) { this.Logger.WarnFormat("ServiceAssembly [{0}] not found! Please check ServiceAssemblyNameAttribute in WindModule.", serviceCommandName.ServiceAssemblyName); continue; } if (shouldBeAssembly != targetServiceType.Assembly) { this.Logger.WarnFormat("Service [{0}] CommandHandler should not be implemented in WindModule [{1}] !", serviceCommandName.FullServiceUniqueName, @interface.Assembly.FullName); continue; } //(严重通过的 IServiceCommandHandler)注册到ServiceBusRegistry this.serviceBusRegistry.RegisterCommand( new ServiceCommandTypeInfo( serviceCommandName, commandType, commandResultType, new IocServiceCommandHandlerFactory(this.iocResolver, targetServiceType)) ); } } //TODO: 注册事件服务 }
private bool dispatchCommand( ServiceUniqueNameInfo commandUniqueName, IRpcMessageSenderContext context, string requestMessageContent, out RemoteServiceBusResponseContext responseContext, out string responseMessageContent, out WindServiceBusRpcException rpcException) { // 创建响应上下文 responseMessageContent = null; rpcException = null; responseContext = new RemoteServiceBusResponseContext(); context.FillRemoteContext(responseContext); // 通过RPC框架执行远程调用 try { RpcTransportMessageRequest requestMessage = new RpcTransportMessageRequest(MessageIdGenerator.CreateMessageId()) { ServiceUniqueName = commandUniqueName, MessageHeader = new RpcTransportMessageHeader { //TODO: 其他消息头 }, MessageContent = requestMessageContent, }; RpcTransportMessageResponse responseMessage = this.rpcServerManager.SendMessage(requestMessage, context); //响应上下文 if (responseMessage != null) { responseContext.FillRemoteContext(responseMessage.MessageHeader); //服务响应信息填入RemoteContext } //响应消息验证 if (responseMessage == null || responseMessage.CorrelationMessageId == null || responseMessage.CorrelationMessageId != requestMessage.MessageId || responseMessage.MessageContent == null) { throw new WindServiceBusException(string.Format("request [{0}] get error response !", requestMessage.MessageId)); } if (responseMessage.ResponseCode != RpcTransportResponseCode.Success) { throw new WindServiceBusException(string.Format("request [{0}] get error response: {1}", requestMessage.MessageId, responseMessage.ErrorInfo)); } responseMessageContent = responseMessage.MessageContent; return(true); //请求成功 } catch (Exception serviceBusException) { this._logger.Error("WindServiceBusException: " + commandUniqueName, serviceBusException); rpcException = new WindServiceBusRpcException(responseContext, serviceBusException); return(false); //请求失败 } }
public ServiceCommandResultWithResponseContext DispatchCommand(Type commandType, Type commandResultType, IServiceCommand commandData) { var commandUniqueName = new ServiceUniqueNameInfo(commandType); //1. 处理请求消息体 string requestMessageContent = this.serializer.SerializeString(commandData); //2. 服务调用 var response = this.DispatchCommand(commandUniqueName, requestMessageContent); //3. 处理响应消息体 var commandResult = (IServiceCommandResult)this.serializer.DeserializeString(commandResultType, response.ResponseMessageContent); return(new ServiceCommandResultWithResponseContext(commandResult, response.ResponseContext)); }
/// <summary> /// 根据目标服务名称,建立请求上下文 /// </summary> /// <param name="targetServiceName">服务名称</param> /// <returns>请求上下文列表</returns> public IList <IRpcMessageSenderContext> BuildSenderContext(ServiceUniqueNameInfo targetServiceName) { IList <ServiceBusServerInfo> busInfoList = this.serviceBusRegistry.DiscoverRemoteBusInfo(targetServiceName.ServiceAssemblyName); if (busInfoList == null || busInfoList.Count < 1) { return(null); //未发现服务,则返回null } //TODO: 考虑路由优先级 var contextList = busInfoList .Where(busInfo => busInfo.ExpoConfig != null && busInfo.ExpoConfig.IsStart) .Select(buildContext) .ToList(); return(contextList); }
/// <summary> /// 构建异常返回消息 /// </summary> public static RpcTransportMessageResponse BuildErrorResponse( ServiceUniqueNameInfo serviceUniqueName, RpcTransportResponseCode errorCode, Exception ex) { if (serviceUniqueName == null) { throw new ArgumentNullException("serviceUniqueName"); } var errorResp = new RpcTransportMessageResponse(MessageIdGenerator.CreateMessageId()) { ResponseCode = errorCode, ServiceUniqueName = serviceUniqueName, ErrorInfo = ex == null ? string.Empty : ex.Message }; return(errorResp); }
public ICollection <ServiceCommandResultWithResponseContext> BroadcastCommand(Type commandType, Type commandResultType, IServiceCommand commandData) { var commandUniqueName = new ServiceUniqueNameInfo(commandType); //1. 处理请求消息体 string requestMessageContent = this.serializer.SerializeString(commandData); //2. 服务调用 var responseCollection = this.BroadcastCommand(commandUniqueName, requestMessageContent); //3. 处理响应消息体 var commandResultCollection = responseCollection.Select(response => { var commandResult = (IServiceCommandResult)this.serializer.DeserializeString(commandResultType, response.ResponseMessageContent); return(new ServiceCommandResultWithResponseContext(commandResult, response.ResponseContext)); }).ToList(); return(commandResultCollection); }
internal ServiceResponseMessageWithResponseContext DispatchCommand(ServiceUniqueNameInfo commandUniqueName, string requestMessageContent) { //1. 服务发现(找到所有可以请求的目标) var remoteContextList = this.rpcServerManager.DiscoverRemoteService(commandUniqueName); if (remoteContextList == null || remoteContextList.Count < 1) { throw new WindServiceBusRemoteServiceNotFoundException(commandUniqueName.FullServiceUniqueName); } //2. 依次尝试发现的目标服务程序集 bool isDispatchSuccess = false; RemoteServiceBusResponseContext responseContext = null; string responseMessageContent = null; List <WindServiceBusRpcException> servicebusExceptionCollection = new List <WindServiceBusRpcException>(); var contextQueue = new Queue <IRpcMessageSenderContext>(remoteContextList); while (!isDispatchSuccess && contextQueue.Count > 0) { var context = contextQueue.Dequeue(); WindServiceBusRpcException busException; isDispatchSuccess = this.dispatchCommand(commandUniqueName, context, requestMessageContent, out responseContext, out responseMessageContent, out busException); if (!isDispatchSuccess && busException != null) { servicebusExceptionCollection.Add(busException); } } if (!isDispatchSuccess) { throw new WindServiceBusMultiRpcException(servicebusExceptionCollection); } return(new ServiceResponseMessageWithResponseContext(responseMessageContent, responseContext)); }
/// <summary> /// 派发服务命令 /// </summary> /// <param name="commandType">命令类型</param> /// <param name="commandResultType">命令响应类型</param> /// <param name="commandData">命令实例</param> /// <returns>命令响应实例</returns> public IServiceCommandResult DispatchCommand(Type commandType, Type commandResultType, IServiceCommand commandData) { var commandName = new ServiceUniqueNameInfo(commandType); ServiceCommandTypeInfo commandTypeInfo; bool isLocalCommandFound = this.registry.IsLocalServiceCommand(commandName, out commandTypeInfo); if (!isLocalCommandFound) { throw new WindServiceBusLocalServiceNotFoundException(commandName.FullServiceUniqueName); } //从本地容器找 IServiceCommandHandlerFactory handlerFactory = commandTypeInfo.CommandHandlerFactory; IServiceCommandHandler commandHandler = handlerFactory.CreateHandler(); //服务实例(命令处理者) try { Type commandHandlerType = typeof(IServiceCommandHandler <,>).MakeGenericType(commandType, commandResultType); MethodInfo method = commandHandlerType.GetMethod("HandlerCommand", new[] { commandType }); var result = (IServiceCommandResult)method.Invoke(commandHandler, new object[] { commandData }); return(result); } catch (Exception ex) { //TODO: 异常处理 if (ex.InnerException != null) { throw ex.InnerException; } throw ex; } finally { //清理服务 handlerFactory.ReleaseHandler(commandHandler); } }
internal ICollection <ServiceResponseMessageWithResponseContext> broadcastRemoteCommand(ServiceUniqueNameInfo serviceName, string requestMessageContent) { var remoteCommandDispatcher = this.createRemoteDispatcher(); return(remoteCommandDispatcher.BroadcastCommand(serviceName, requestMessageContent)); }
/// <summary> /// 广播命令 /// </summary> internal ICollection <ServiceResponseMessageWithResponseContext> BroadcastCommand(ServiceUniqueNameInfo commandUniqueName, string requestMessageContent) { //1. 服务发现(找到所有可以请求的目标) var remoteContextList = this.rpcServerManager.DiscoverRemoteService(commandUniqueName); if (remoteContextList == null || remoteContextList.Count < 1) { return(new ServiceResponseMessageWithResponseContext[0]); //throw new WindServiceBusRemoteServiceNotFoundException(commandUniqueName.FullServiceUniqueName); } //2. 广播请求 RpcTransportMessageRequest requestMessage = new RpcTransportMessageRequest(MessageIdGenerator.CreateMessageId()) { ServiceUniqueName = commandUniqueName, MessageHeader = new RpcTransportMessageHeader { //TODO: 其他消息头 }, MessageContent = requestMessageContent, }; ICollection <RpcTransportErrorResponse> errorCollection; var responseCollection = this.rpcServerManager.BroadcastMessage(requestMessage, remoteContextList, out errorCollection); var resultList = responseCollection.Select(resp => new ServiceResponseMessageWithResponseContext(resp.MessageContent, new RemoteServiceBusResponseContext(resp.MessageHeader))).ToList(); if (errorCollection != null && errorCollection.Count > 0) { //TODO: 异常列表返回处理 } return(resultList); }
public void DoCommandStub(CommandHeader header, object[] inputArgs, out object[] outputArgs) { var commandId = header.CommandId; var appClass = header.AppClass; if (commandId == (uint)ExpoCommandName.ServiceBusCommand) { //获取请求输入 var expoInput = new ExpoCommandMessageParser.ExpoMessageInput(inputArgs); try { //处理请求命令 var commandProcessor = this.iocResolver.Resolve <RemoteServiceCommandProcessor>(); var rpcRequest = expoInput.BuidRpcTransportMessage(); //构建请求环境 this.fillRequestRemoteContext(header, rpcRequest.MessageHeader); //处理并返回 var rpcResponse = commandProcessor.ProcessCommand(rpcRequest); //返回命令响应 outputArgs = (new ExpoCommandMessageParser.ExpoMessageOutput(rpcResponse)).BuidExpoMessageBody(); } catch (Exception ex) { //返回异常响应 var serviceUniqueName = new ServiceUniqueNameInfo(expoInput.ServiceAssemblyName, expoInput.ServiceCommandName, ServiceUniqueNameInfo.ServiceMessageType.ServiceCommand); var errorResp = RpcTransportMessageResponse.BuildErrorResponse(serviceUniqueName, RpcTransportResponseCode.SystemError, ex); outputArgs = (new ExpoCommandMessageParser.ExpoMessageOutput(errorResp)).BuidExpoMessageBody(); this.Logger.Error(serviceUniqueName.ToString(), ex); } } else if (commandId == (uint)ExpoCommandName.ServiceBusBroadcastCommand) { //获取请求输入 var expoInput = new ExpoCommandMessageParser.ExpoMessageInput(inputArgs); try { //处理请求命令 var commandProcessor = this.iocResolver.Resolve <RemoteServiceCommandProcessor>(); var rpcRequest = expoInput.BuidRpcTransportMessage(); //构建请求环境 this.fillRequestRemoteContext(header, rpcRequest.MessageHeader); //处理并返回 var rpcResponse = commandProcessor.ProcessBroadcastCommand(rpcRequest); //返回命令响应 outputArgs = (new ExpoCommandMessageParser.ExpoMessageOutput(rpcResponse)).BuidExpoMessageBody(); } catch (Exception ex) { //返回异常响应 var serviceUniqueName = new ServiceUniqueNameInfo(expoInput.ServiceAssemblyName, expoInput.ServiceCommandName, ServiceUniqueNameInfo.ServiceMessageType.ServiceCommand); var errorResp = RpcTransportMessageResponse.BuildErrorResponse(serviceUniqueName, RpcTransportResponseCode.SystemError, ex); outputArgs = (new ExpoCommandMessageParser.ExpoMessageOutput(errorResp)).BuidExpoMessageBody(); this.Logger.Error(serviceUniqueName.ToString(), ex); } } else if (commandId == (uint)ExpoCommandName.ISellerLegacyCommand) { var commandProcessor = this.iocResolver.Resolve <ISellerCommandProcessor>(); string jsonRequest = Encoding.Default.GetString(inputArgs[0] as byte[]); ISellerExpoRequest request = ISellerExpoRequest.ConvertFromJson(jsonRequest); ISellerExpoResponse response = commandProcessor.ProcessCommand(request, messageHeader => { //构建请求环境 this.fillRequestRemoteContext(header, messageHeader); }); outputArgs = new object[] { Encoding.Default.GetBytes(response.ConvertToJson()) }; } else { throw new WindServiceBusException(string.Format("EXPO命令:[{0}]无法识别!", commandId)); } }