예제 #1
0
        /// <summary>
        /// grpc方法调用
        /// </summary>
        public async Task <string> MethodInvoke(string endpoint, string methodName, string requestJson, Dictionary <string, string> customHeaders)
        {
            var channel = new Channel(endpoint, ChannelCredentials.Insecure);

            try
            {
                var client   = new BaseServiceClient(channel);
                var metadata = new Metadata();
                foreach (var item in customHeaders)
                {
                    if (!metadata.Any(p => p.Key == item.Key))
                    {
                        metadata.Add(new Metadata.Entry(item.Key, item.Value));
                    }
                }
                return((await client.MethodInvokeAsync(new MethodInvokeRQ
                {
                    FullName = methodName,
                    RequestJson = requestJson
                }, metadata
                                                       // , deadline: DateTime.UtcNow.AddSeconds(_grpcTimeout)
                                                       )).ResponseJson);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(ex.ToString());
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
예제 #2
0
        /// <summary>
        /// 获取服务基本信息
        /// </summary>
        public async Task <InfoRS> GetInfo(string address, int port)
        {
            var channel = new Channel(address, port, ChannelCredentials.Insecure);

            try
            {
                var client = new BaseServiceClient(channel);
                return(await client.InfoAsync(new InfoRQ { MethodName = "" }, deadline : DateTime.UtcNow.AddSeconds(_config.GetValue <int>("GrpcTimeout"))));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(null);
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
예제 #3
0
        /// <summary>
        /// 获取方法信息
        /// </summary>
        public MethodInfoRS GetMethodInfo(string endpoint, string methodName)
        {
            var channel = new Channel(endpoint, ChannelCredentials.Insecure);

            try
            {
                var client = new BaseServiceClient(channel);
                return(client.MethodInfo(new MethodInfoRQ
                {
                    FullName = methodName
                }, deadline: DateTime.UtcNow.AddSeconds(_config.GetValue <int>("GrpcTimeout"))));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(null);
            }
            finally
            {
                channel.ShutdownAsync().Wait();
            }
        }
예제 #4
0
        /// <summary>
        /// 获取方法信息
        /// </summary>
        public async Task <MethodInfoRS> GetMethodInfo(string endpoint, string methodName)
        {
            var channel = new Channel(endpoint, ChannelCredentials.Insecure);

            try
            {
                var client = new BaseServiceClient(channel);
                return(await client.MethodInfoAsync(new MethodInfoRQ
                {
                    FullName = methodName
                }, deadline : DateTime.UtcNow.AddSeconds(_grpcTimeout)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                throw ex;
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
예제 #5
0
        /// <summary>
        /// grpc方法调用
        /// </summary>
        public string MethodInvoke(string endpoint, string methodName, string requestJson)
        {
            var channel = new Channel(endpoint, ChannelCredentials.Insecure);

            try
            {
                var client = new BaseServiceClient(channel);
                return(client.MethodInvoke(new MethodInvokeRQ
                {
                    FullName = methodName,
                    RequestJson = requestJson
                } /*, deadline: DateTime.UtcNow.AddSeconds(_config.GetValue<int>("GrpcTimeout"))*/).ResponseJson);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(ex.ToString());
            }
            finally
            {
                channel.ShutdownAsync().Wait();
            }
        }
예제 #6
0
        private void InitComm()
        {
            if (string.IsNullOrEmpty(_clientName))
            {
                _clientName = getLocalIPAddress();
            }
            if (string.IsNullOrEmpty(_pluginName))
            {
                _pluginName = "InvalidPlugin";//没有设置插件名的连接,默认为无效插件InvalidPlugin
            }
            if (string.IsNullOrEmpty(_wcfendpoint))
            {
                _wcfendpoint = "wcfendpoint";
            }
            if (string.IsNullOrEmpty(_fileendpoint))
            {
                _fileendpoint = "fileendpoint";
            }

            //PluginName = pluginname;

            clientObj            = new ClientObject();
            clientObj.ClientName = _clientName;
            clientObj.RouterID   = Guid.NewGuid().ToString();
            clientObj.PluginName = PluginName;
            //clientObj.Token = _token;


#if ClientProxy
            baseServiceClient = new BaseServiceClient(_wcfendpoint);
#else
            clientObj.ReplyService = new ReplyDataCallback(this);
            baseServiceClient      = new DuplexBaseServiceClient(clientObj.ReplyService, _wcfendpoint);
#endif
            //if (fileServiceClient == null)
            fileServiceClient = new FileServiceClient(_fileendpoint);
        }
예제 #7
0
        /// <summary>
        /// 保持响应
        /// </summary>
        public Tuple <bool, string> SaveResponse(string serviceName, string methodName, bool isSaveResponse)
        {
            var srv = _consulSrv.GetService(serviceName).Result;

            if (srv == null || srv.Count == 0)
            {
                return(Tuple.Create(false, $"consul中找不到服务({serviceName})"));
            }

            var result = true;
            var msg    = "";

            foreach (var item in srv)
            {
                var channel = new Channel(item.Address, item.Port, ChannelCredentials.Insecure);
                try
                {
                    var client = new BaseServiceClient(channel);
                    var res    = client.AddDelSaveResponseEnable(new AddDelSaveResponseEnableRQ
                    {
                        MethodName = methodName,
                        IsDel      = !isSaveResponse
                    }, deadline: DateTime.UtcNow.AddSeconds(_config.GetValue <int>("GrpcTimeout")));
                }
                catch (Exception ex)
                {
                    result = false;
                    msg   += $"{item.Address};{item.Port}执行失败" + Environment.NewLine;
                    _logger.LogError(ex, ex.Message);
                }
                finally
                {
                    channel.ShutdownAsync().Wait();
                }
            }
            return(Tuple.Create(result, msg));
        }
예제 #8
0
 public BaseClientLL(Channel channel) : base(channel)
 {
     client = new BaseServiceClient(channel);
 }
예제 #9
0
        /// <summary>
        /// 向服务发送异步请求
        /// 客户端建议不要用多线程,都采用异步请求方式
        /// </summary>
        /// <param name="controller">插件名@控制器名称</param>
        /// <param name="method">方法名称</param>
        /// <param name="jsondata">数据</param>
        /// <returns>返回Json数据</returns>
        public IAsyncResult RequestAsync(string controller, string method, Action <ClientRequestData> requestAction, Action <ServiceResponseData> action)
        {
            if (clientObj == null)
            {
                throw new Exception("还没有创建连接!");
            }
            try
            {
                ClientRequestData requestData = new ClientRequestData(serverConfig.IsCompressJson, serverConfig.IsEncryptionJson, (SerializeType)serverConfig.SerializeType);
                if (requestAction != null)
                {
                    requestAction(requestData);
                }

                string jsondata = requestData.GetJsonData();      //获取序列化的请求数据

                if (requestData.Iscompressjson)                   //开启压缩
                {
                    jsondata = ZipComporessor.Compress(jsondata); //压缩传入参数
                }
                if (requestData.Isencryptionjson)                 //开启加密
                {
                    DESEncryptor des = new DESEncryptor();
                    des.InputString = jsondata;
                    des.DesEncrypt();
                    jsondata = des.OutString;
                }
#if ClientProxy
                BaseServiceClient _wcfService     = clientObj.WcfService;
                IContextChannel   iContextChannel = _wcfService.InnerChannel;
#else
                DuplexBaseServiceClient _wcfService     = clientObj.WcfService;
                IContextChannel         iContextChannel = _wcfService.InnerDuplexChannel;
#endif
                IAsyncResult result = null;

                AddMessageHeader(iContextChannel as IContextChannel, "", requestData.Iscompressjson, requestData.Isencryptionjson, requestData.Serializetype, requestData.LoginRight, (() =>
                {
                    AsyncCallback callback = delegate(IAsyncResult r)
                    {
                        string retJson = _wcfService.EndProcessRequest(r);

                        if (requestData.Isencryptionjson)//解密结果
                        {
                            DESEncryptor des = new DESEncryptor();
                            des.InputString = retJson;
                            des.DesDecrypt();
                            retJson = des.OutString;
                        }
                        if (requestData.Iscompressjson)//解压结果
                        {
                            retJson = ZipComporessor.Decompress(retJson);
                        }

                        string retData = "";
                        object Result = JsonConvert.DeserializeObject(retJson);
                        int ret = Convert.ToInt32((((Newtonsoft.Json.Linq.JObject)Result)["flag"]).ToString());
                        string msg = (((Newtonsoft.Json.Linq.JObject)Result)["msg"]).ToString();
                        if (ret == 1)
                        {
                            throw new Exception(msg);
                        }
                        else
                        {
                            retData = ((Newtonsoft.Json.Linq.JObject)(Result))["data"].ToString();
                        }

                        ServiceResponseData responsedata = new ServiceResponseData();
                        responsedata.Iscompressjson = requestData.Iscompressjson;
                        responsedata.Isencryptionjson = requestData.Isencryptionjson;
                        responsedata.Serializetype = requestData.Serializetype;
                        responsedata.SetJsonData(retData);

                        action(responsedata);
                    };
                    result = _wcfService.BeginProcessRequest(clientObj.ClientID, clientObj.PluginName, controller, method, jsondata, callback, null);
                }));

                new Action(delegate()
                {
                    if (serverConfig.IsHeartbeat == false)//如果没有启动心跳,则请求发送心跳
                    {
                        ServerConfigRequestState = false;
                        Heartbeat();
                    }
                }).BeginInvoke(null, null);//异步执行

                return(result);
            }
            catch (Exception e)
            {
                ServerConfigRequestState = false;
                ReConnection(true);//连接服务主机失败,重连
                throw new Exception(e.Message + "\n连接服务主机失败,请联系管理员!");
            }
        }
예제 #10
0
        /// <summary>
        /// 向服务发送请求
        /// </summary>
        /// <param name="controller">控制器名称</param>
        /// <param name="method">方法名称</param>
        /// <param name="requestAction">数据</param>
        /// <returns>返回Json数据</returns>
        public ServiceResponseData Request(string controller, string method, Action <ClientRequestData> requestAction)
        {
            if (clientObj == null)
            {
                throw new Exception("还没有创建连接!");
            }
            while (baseServiceClient.State == CommunicationState.Opening || clientObj.ClientID == null)//解决并发问题
            {
                Thread.Sleep(400);
            }

            if (baseServiceClient.State == CommunicationState.Closed || baseServiceClient.State == CommunicationState.Faulted)
            {
                ReConnection(true);//连接服务主机失败,重连
            }
            try
            {
                ClientRequestData requestData = new ClientRequestData(serverConfig.IsCompressJson, serverConfig.IsEncryptionJson, (SerializeType)serverConfig.SerializeType);
                if (requestAction != null)
                {
                    requestAction(requestData);
                }

                string jsondata = requestData.GetJsonData();      //获取序列化的请求数据

                if (requestData.Iscompressjson)                   //开启压缩
                {
                    jsondata = ZipComporessor.Compress(jsondata); //压缩传入参数
                }
                if (requestData.Isencryptionjson)                 //开启加密
                {
                    DESEncryptor des = new DESEncryptor();
                    des.InputString = jsondata;
                    des.DesEncrypt();
                    jsondata = des.OutString;
                }
                string retJson = "";
#if ClientProxy
                BaseServiceClient _wcfService = clientObj.WcfService;
                AddMessageHeader(_wcfService.InnerChannel as IContextChannel, "", requestData.Iscompressjson, requestData.Isencryptionjson, requestData.Serializetype, requestData.LoginRight, (() =>
                {
                    retJson = _wcfService.ProcessRequest(clientObj.ClientID, clientObj.PluginName, controller, method, jsondata);
                }));
#else
                DuplexBaseServiceClient _wcfService = clientObj.WcfService;
                AddMessageHeader(_wcfService.InnerDuplexChannel as IContextChannel, "", requestData.Iscompressjson, requestData.Isencryptionjson, requestData.Serializetype, requestData.LoginRight, (() =>
                {
                    retJson = _wcfService.ProcessRequest(clientObj.ClientID, clientObj.PluginName, controller, method, jsondata);
                }));
#endif
                if (requestData.Isencryptionjson)//解密结果
                {
                    DESEncryptor des = new DESEncryptor();
                    des.InputString = retJson;
                    des.DesDecrypt();
                    retJson = des.OutString;
                }
                if (requestData.Iscompressjson)//解压结果
                {
                    retJson = ZipComporessor.Decompress(retJson);
                }

                new Action(delegate()
                {
                    if (serverConfig.IsHeartbeat == false)//如果没有启动心跳,则请求发送心跳
                    {
                        ServerConfigRequestState = false;
                        Heartbeat();
                    }
                }).BeginInvoke(null, null);//异步执行

                string retData = "";
                object Result  = JsonConvert.DeserializeObject(retJson);
                int    ret     = Convert.ToInt32((((Newtonsoft.Json.Linq.JObject)Result)["flag"]).ToString());
                string msg     = (((Newtonsoft.Json.Linq.JObject)Result)["msg"]).ToString();
                if (ret == 1)
                {
                    throw new Exception(msg);
                }
                else
                {
                    retData = ((Newtonsoft.Json.Linq.JObject)(Result))["data"].ToString();
                }

                ServiceResponseData responsedata = new ServiceResponseData();
                responsedata.Iscompressjson   = requestData.Iscompressjson;
                responsedata.Isencryptionjson = requestData.Isencryptionjson;
                responsedata.Serializetype    = requestData.Serializetype;
                responsedata.SetJsonData(retData);

                return(responsedata);
            }
            catch (Exception e)
            {
                ServerConfigRequestState = false;
                //ReConnection(true);//连接服务主机失败,重连
                //throw new Exception(e.Message + "\n连接服务主机失败,请联系管理员!");
                throw new Exception(e.Message);
            }
        }
예제 #11
0
 protected IEnumerable<Project> LoadProjects() {
     BaseServiceClient client = new BaseServiceClient();
     return client.Projects();
 }