Ejemplo n.º 1
0
 /// <summary>
 /// 关闭连接,请慎用,这个主要是提供给连接池管理用来释放连接的
 /// 业务千万不能用这个
 /// </summary>
 public void Close()
 {
     isConnected = false;
     try
     {
         if (transport != null)
         {
             if (transport.IsOpen)
             {
                 transport.Close();
             }
             transport.Dispose();
             transport = null;
         }
         if (client != null)
         {
             client.Dispose();
             client = null;
         }
     }
     catch (Exception ex)
     {
         logger.LogError(ex, "SuperGMS.GrantRpc.Thrift.Client.Dispose.Error");
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// 关闭连接,请慎用,这个主要是提供给连接池管理用来释放连接的
 /// 业务千万不能用这个
 /// </summary>
 public void Close()
 {
     isConnected = false;
     try
     {
         if (transport != null)
         {
             if (transport.IsOpen)
             {
                 transport.Close();
             }
             transport.Dispose();
             logger.LogDebug($"关闭链接:{transport.GetHashCode()},{clientItem.Ip}:{clientItem.Port}");
             transport = null;
         }
         if (client != null)
         {
             client.Dispose();
             client = null;
         }
     }
     catch (Exception ex)
     {
         logger.LogError(ex, "GrantMicroService.GrantRpc.Thrift.Client.Dispose.Error");
     }
 }
Ejemplo n.º 3
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         SafeAction(() => _transport.Dispose());
     }
 }
 public void Close()
 {
     if (transport != null)
     {
         transport.Close();
         transport.Dispose();
     }
 }
Ejemplo n.º 5
0
 //初始化
 public bool Init()
 {
     lock (this)
     {
         try
         {
             transport = new TSocket(m_host, m_port, m_timeout);
             protocol  = new TBinaryProtocol(transport);
             TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "SercurityService");
             SercurityClient = new SercurityService.Client(mp);
             TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "SaleService");
             SaleClient = new SaleService.Client(mp2);
             TMultiplexedProtocol mp3 = new TMultiplexedProtocol(protocol, "DataSyncService");
             DataSyncClient = new DataSyncService.Client(mp3);
             if (transport != null && !transport.IsOpen)
             {
                 transport.Open();
             }
             return(true);
         }
         catch (Exception ex)
         {
             if (transport != null)
             {
                 transport.Dispose();
             }
             if (protocol != null)
             {
                 protocol.Dispose();
             }
             if (DataSyncClient != null)
             {
                 DataSyncClient.Dispose();
             }
             if (SaleClient != null)
             {
                 SaleClient.Dispose();
             }
             if (SercurityClient != null)
             {
                 SercurityClient.Dispose();
             }
             if (SystemClient != null)
             {
                 SystemClient.Dispose();
             }
             transport       = null;
             protocol        = null;
             SercurityClient = null;
             SystemClient    = null;
             SaleClient      = null;
             DataSyncClient  = null;
             _log.Error(ex.Message.ToString());
             return(false);
         }
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// destory the instance.
 /// </summary>
 /// <param name="instance"></param>
 private void DestoryInstance(TTransport instance)
 {
     instance.Flush();
     if (instance.IsOpen)
     {
         instance.Close();
     }
     instance.Dispose();
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Close Connection
 /// </summary>
 public static void TransportClose()
 {
     if (_transport == null)
     {
         return;
     }
     if (_transport.IsOpen)
     {
         _transport.Close();
     }
     _transport.Dispose();
 }
Ejemplo n.º 8
0
        public void Dispose()
        {
            if (_transport != null)
            {
                _transport.Dispose();
            }

            if (_protocol != null)
            {
                _protocol.Dispose();
            }
        }
Ejemplo n.º 9
0
 // IDisposable
 protected override void Dispose(bool disposing)
 {
     if (!_isDisposed)
     {
         if (disposing)
         {
             _inputBuffer?.Dispose();
             _outputBuffer?.Dispose();
             _transport?.Dispose();
         }
     }
     _isDisposed = true;
 }
Ejemplo n.º 10
0
 // IDisposable
 protected override void Dispose(bool disposing)
 {
     if (!_isDisposed)
     {
         if (disposing)
         {
             _readBuffer?.Dispose();
             _writeBuffer?.Dispose();
             _transport?.Dispose();
         }
     }
     _isDisposed = true;
 }
Ejemplo n.º 11
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }
            if (disposing)
            {
                _inPipe?.Dispose();
            }

            _disposed = true;
        }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="ErrObj">Exception Class</typeparam>
        /// <typeparam name="TResult">Return Object</typeparam>
        /// <param name="transport">socket</param>
        /// <param name="thriftOpt">thriftservice interface</param>
        /// <param name="methodName">exception method</param>
        /// <returns></returns>
        public static TResult GetResult <ErrObj, TResult>(TTransport transport, Func <TResult> thriftOpt, string methodName, bool isAppearErr)
            where TResult : new()
            where ErrObj : class
        {
            TResult t = new TResult();

            try
            {
                if (!transport.IsOpen)
                {
                    transport.Open();
                }
                if (thriftOpt != null)
                {
                    t = thriftOpt.Invoke();
                }
            }
            catch (Exception ex)
            {
                Logger <ErrObj> .Log.Error(methodName, ex);

                //测试环境下给予提示
                //methodName heart
                if (isAppearErr)
                {
                    if ("DEBUG".Equals(GlobalCache.AppMode))
                    {
                        if (!"HearBeat".Equals(methodName))
                        {
                            ExceptionMsgFromSTAThread(methodName);
                        }
                    }
                    else
                    {
                        if (!"HearBeat".Equals(methodName))
                        {
                            ExceptionMsgFromSTAThread(methodName, null);
                        }
                    }
                }
            }
            finally
            {
                transport.Close();
                transport.Dispose();
            }

            return(t);
        }
Ejemplo n.º 13
0
 protected void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             if (transport != null && transport.IsOpen)
             {
                 transport.Close();
                 transport.Dispose();
             }
         }
         disposed = true;
     }
 }
Ejemplo n.º 14
0
 //释放链接
 public void Dispose()
 {
     lock (this)
     {
         try
         {
             if (transport != null && transport.IsOpen)
             {
                 transport.Close();
             }
             if (transport != null)
             {
                 transport.Dispose();
             }
             if (protocol != null)
             {
                 protocol.Dispose();
             }
             if (DataSyncClient != null)
             {
                 DataSyncClient.Dispose();
             }
             if (SaleClient != null)
             {
                 SaleClient.Dispose();
             }
             if (SercurityClient != null)
             {
                 SercurityClient.Dispose();
             }
             if (SystemClient != null)
             {
                 SystemClient.Dispose();
             }
             transport       = null;
             protocol        = null;
             SercurityClient = null;
             SystemClient    = null;
             SaleClient      = null;
             DataSyncClient  = null;
         }
         catch (Exception ex)
         {
             throw new Exception(ex.Message.ToString());
         }
     }
 }
Ejemplo n.º 15
0
 private void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             try
             {
                 transport.Close();
                 transport.Dispose();
             }
             catch (Exception)
             {
                 //var x = ex;
             }
         }
         disposed = true;
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// 更新服务缓存
        /// </summary>
        /// <param name="channel">管道</param>
        internal static void UpdateCache(string channel)
        {
            #region 到DNS中心取服务信息
            try
            {
                if (channel.Equals("cron:"))
                {
                    RefreshServiceMd5();
                    channel = ServiceMd5;
                }
                if (!_proxyCenter.IsOpen)
                {
                    _proxyCenter.Open();
                }
                DateTime now       = DateTime.Now; //获取缓存时间
                var      microList = _client.GetMicro(channel);
                #region Micro +添加到缓存

                if (microList != null && microList.Count > 0)
                {
                    var microCaches = new List <MicroCache>();
                    microList.ForEach(m =>
                    {
                        microCaches.Add(new MicroCache()
                        {
                            LasTime = now,
                            Mi      = m,
                            Tags    = m.Name.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(t => t.Substring(0, t.Length - 7)).ToList()
                        });
                    });
                    _microCaches = microCaches;

                    #region  步服务到连接池
                    var scs = new List <ServiceConfig>();
                    _microCaches.ForEach(mc =>
                    {
                        if (!scs.Exists(s => s.Host == mc.Mi.Ip && s.Port == mc.Mi.Port))
                        {
                            scs.Add(new ServiceConfig()
                            {
                                Host    = mc.Mi.Ip,
                                Port    = mc.Mi.Port,
                                Timeout = mc.Mi.Timeout
                            });
                        }
                    });
                    ThriftFactory.Synchronization(scs);

                    #endregion
                }
                else
                {
                    _microCaches.Clear();
                    ThriftFactory.Synchronization(new List <ServiceConfig>());
                }

                #endregion
            }
            catch (Exception ex)
            {
                try
                {
                    if (connectionCenterInit == false)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkYellow;
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + $":注册中心 {SettingService.Local.IpAddress}:{SettingService.Local.Port} " + ex.Message);
                        Console.ResetColor();
                        connectionCenterInit = true;
                    }
                    // return (null, FailMessage($"负载中心连接失败!"));
                    if (_proxyCenter.IsOpen)
                    {
                        _proxyCenter.Flush();
                        _proxyCenter.Close();
                    }

                    _proxyCenter.Dispose();

                    _proxyCenter = new TSocket(SettingService.Local.IpAddress, SettingService.Local.Port, 30000);
                    _protocol    = new TBinaryProtocol(_proxyCenter);
                    _client      = new BrokerCenter.Client(_protocol);
                }
                catch
                {
                    // ignored
                }
            }
            #endregion
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Loops on processing a client forever
        /// threadContext will be a TTransport instance
        /// </summary>
        /// <param name="threadContext"></param>
        private void Execute(Object threadContext)
        {
            using (TTransport client = (TTransport)threadContext)
            {
                TProcessor processor         = processorFactory.GetProcessor(client, this);
                TTransport inputTransport    = null;
                TTransport outputTransport   = null;
                TProtocol  inputProtocol     = null;
                TProtocol  outputProtocol    = null;
                Object     connectionContext = null;
                try
                {
                    try
                    {
                        inputTransport  = inputTransportFactory.GetTransport(client);
                        outputTransport = outputTransportFactory.GetTransport(client);
                        inputProtocol   = inputProtocolFactory.GetProtocol(inputTransport);
                        outputProtocol  = outputProtocolFactory.GetProtocol(outputTransport);

                        //Recover event handler (if any) and fire createContext server event when a client connects
                        if (serverEventHandler != null)
                        {
                            connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol);
                        }

                        //Process client requests until client disconnects
                        while (!stop)
                        {
                            if (!inputTransport.Peek())
                            {
                                break;
                            }

                            //Fire processContext server event
                            //N.B. This is the pattern implemented in C++ and the event fires provisionally.
                            //That is to say it may be many minutes between the event firing and the client request
                            //actually arriving or the client may hang up without ever makeing a request.
                            if (serverEventHandler != null)
                            {
                                serverEventHandler.processContext(connectionContext, inputTransport);
                            }
                            //Process client request (blocks until transport is readable)
                            if (!processor.Process(inputProtocol, outputProtocol))
                            {
                                break;
                            }
                        }
                    }
                    catch (TTransportException)
                    {
                        //Usually a client disconnect, expected
                    }
                    catch (Exception x)
                    {
                        //Unexpected
                        logDelegate("Error: " + x);
                    }

                    //Fire deleteContext server event after client disconnects
                    if (serverEventHandler != null)
                    {
                        serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol);
                    }
                }
                finally
                {
                    //Close transports
                    if (inputTransport != null)
                    {
                        inputTransport.Close();
                    }
                    if (outputTransport != null)
                    {
                        outputTransport.Close();
                    }

                    // disposable stuff should be disposed
                    if (inputProtocol != null)
                    {
                        inputProtocol.Dispose();
                    }
                    if (outputProtocol != null)
                    {
                        outputProtocol.Dispose();
                    }
                    if (inputTransport != null)
                    {
                        inputTransport.Dispose();
                    }
                    if (outputTransport != null)
                    {
                        outputTransport.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Loops on processing a client forever
        /// client will be a TTransport instance
        /// </summary>
        /// <param name="client"></param>
        private async Task ExecuteAsync(TTransport client)
        {
            var cancellationToken = ServerCancellationToken;

            var processor = ProcessorFactory.GetAsyncProcessor(client, this);

            TTransport inputTransport    = null;
            TTransport outputTransport   = null;
            TProtocol  inputProtocol     = null;
            TProtocol  outputProtocol    = null;
            object     connectionContext = null;

            try
            {
                try
                {
                    inputTransport  = InputTransportFactory.GetTransport(client);
                    outputTransport = OutputTransportFactory.GetTransport(client);
                    inputProtocol   = InputProtocolFactory.GetProtocol(inputTransport);
                    outputProtocol  = OutputProtocolFactory.GetProtocol(outputTransport);

                    //Recover event handler (if any) and fire createContext server event when a client connects
                    if (ServerEventHandler != null)
                    {
                        connectionContext = await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken);
                    }

                    //Process client requests until client disconnects
                    while (!(stop || cancellationToken.IsCancellationRequested))
                    {
                        if (!await inputTransport.PeekAsync(cancellationToken))
                        {
                            break;
                        }

                        //Fire processContext server event
                        //N.B. This is the pattern implemented in C++ and the event fires provisionally.
                        //That is to say it may be many minutes between the event firing and the client request
                        //actually arriving or the client may hang up without ever makeing a request.
                        if (ServerEventHandler != null)
                        {
                            await ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken);
                        }

                        //Process client request (blocks until transport is readable)
                        if (!await processor.ProcessAsync(inputProtocol, outputProtocol, cancellationToken))
                        {
                            break;
                        }
                    }
                }
                catch (TTransportException)
                {
                    //Usually a client disconnect, expected
                }
                catch (Exception x)
                {
                    //Unexpected
                    LogError("Error: " + x);
                }

                //Fire deleteContext server event after client disconnects
                if (ServerEventHandler != null)
                {
                    await ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol, cancellationToken);
                }
            }
            finally
            {
                //Close transports
                inputTransport?.Close();
                outputTransport?.Close();

                // disposable stuff should be disposed
                inputProtocol?.Dispose();
                outputProtocol?.Dispose();
                inputTransport?.Dispose();
                outputTransport?.Dispose();
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="target">注册目标</param>
        /// <param name="countDown">注册超时次数</param>
        /// <returns></returns>
        public bool ToCenter(Target target, int countDown = 10)
        {
begin:
            try
            {
                _transport = new TSocket(target.IpAddress, target.Port, 3000);
                TProtocol protocol = new TBinaryProtocol(_transport);
                _client = new BrokerCenter.Client(protocol);

                if (!_transport.IsOpen)
                {
                    _transport.Open();
                }
                Dictionary <string, string> info = new Dictionary <string, string>
                {
                    { "timeout", SettingService.TimeOut.ToString() },
                    { "name", SettingService.FuncName },
                    { "ip", SettingService.Local.IpAddress == null?GetLocalIps() : SettingService.Local.IpAddress },
                    { "port", SettingService.Local.Port.ToString() },
                    { "weight", SettingService.Weight.ToString() },
                    { "nickname", SettingService.AppName }
                };
                bool rlt = _client.add_broker(info);
                _transport.Close();
                if (rlt)
                {
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    Console.WriteLine($"{DateTime.Now}");
                    Console.WriteLine($"本机【{SettingService.AppName}】:");
                    foreach (var ip in info["ip"].Split(','))
                    {
                        Console.WriteLine($"{ip}");
                    }
                    Console.WriteLine($"已注册到:{target.IpAddress}");
                    Console.ResetColor();
                    Console.WriteLine($"----------------------------------------------------------------- ");
                }
                return(rlt);
            }
            catch (Exception ex)
            {
                Thread.Sleep(1000);//间隔一秒后重新注册
                if (countDown > 0)
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine($"{DateTime.Now} 注册到{target.IpAddress}:{target.Port}失败......剩余重试次数({countDown})");
                    Console.WriteLine($"错误信息:{ex.Message}");
                    Console.ResetColor();
                    try
                    {
                        if (_transport.IsOpen)
                        {
                            _transport.Close();
                        }
                        _transport.Dispose();
                    }
                    catch
                    {
                        //忽略异常
                    }
                    --countDown;
                    goto begin;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine($"{DateTime.Now} 未连接到{target.IpAddress}:{target.Port}注册失败......");
                    Console.ResetColor();
                }
            }
            finally
            {
                try
                {
                    if (_transport.IsOpen)
                    {
                        _transport.Close();
                    }
                    _transport.Dispose();
                }
                catch
                {
                    //忽略异常
                }
            }
            return(true);
        }
Ejemplo n.º 20
0
        private async Task Execute(TTransport client, CancellationToken cancellationToken)
        {
            Logger.LogTrace("Started client request processing");

            var processor = ProcessorFactory.GetAsyncProcessor(client, this);

            TTransport inputTransport    = null;
            TTransport outputTransport   = null;
            TProtocol  inputProtocol     = null;
            TProtocol  outputProtocol    = null;
            object     connectionContext = null;

            try
            {
                try
                {
                    inputTransport  = InputTransportFactory.GetTransport(client);
                    outputTransport = OutputTransportFactory.GetTransport(client);
                    inputProtocol   = InputProtocolFactory.GetProtocol(inputTransport);
                    outputProtocol  = OutputProtocolFactory.GetProtocol(outputTransport);

                    if (ServerEventHandler != null)
                    {
                        connectionContext = await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken);
                    }

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        if (!await inputTransport.PeekAsync(cancellationToken))
                        {
                            break;
                        }

                        if (ServerEventHandler != null)
                        {
                            await ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken);
                        }

                        if (!await processor.ProcessAsync(inputProtocol, outputProtocol, cancellationToken))
                        {
                            break;
                        }
                    }
                }
                catch (TTransportException ttx)
                {
                    Logger.LogTrace($"Transport exception: {ttx}");
                }
                catch (Exception x)
                {
                    Logger.LogError($"Error: {x}");
                }

                if (ServerEventHandler != null)
                {
                    await ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol, cancellationToken);
                }
            }
            finally
            {
                //Close transports
                inputTransport?.Close();
                outputTransport?.Close();

                // disposable stuff should be disposed
                inputProtocol?.Dispose();
                outputProtocol?.Dispose();
                inputTransport?.Dispose();
                outputTransport?.Dispose();
            }

            Logger.LogTrace("Completed client request processing");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="target">注册目标</param>
        /// <param name="countDown">注册超时次数</param>
        /// <returns></returns>
        public bool ToCenter(Target target, int countDown = 10)
        {
begin:
            try
            {
                _transport = new TSocket(target.IpAddress, target.Port, 3000);
                TProtocol protocol = new TBinaryProtocol(_transport);
                _client = new BrokerCenter.Client(protocol);

                if (!_transport.IsOpen)
                {
                    _transport.Open();
                }
                Dictionary <string, string> info = new Dictionary <string, string>
                {
                    { "timeout", SettingService.TimeOut.ToString() },
                    { "name", SettingService.FuncName },
                    { "ip", SettingService.Local.IpAddress == null?GetLocalIps() : SettingService.Local.IpAddress },
                    { "port", SettingService.Local.Port.ToString() },
                    { "weight", SettingService.Weight.ToString() },
                    { "nickname", SettingService.AppName }
                };
                bool rlt = _client.add_broker(info);
                _transport.Close();
                if (rlt)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine($"本机【{SettingService.AppName}】:");
                    foreach (var ip in info["ip"].Split(','))
                    {
                        stringBuilder.AppendLine($"{ip}");
                    }
                    stringBuilder.AppendLine($"已注册到:{target.IpAddress}");
                    Log.Anno(stringBuilder.ToString(), typeof(Register));
                    Log.WriteLine($"已注册到:{target.IpAddress}");
                }
                return(rlt);
            }
            catch (Exception ex)
            {
                Task.Delay(1000).Wait();//间隔一秒后重新注册
                if (countDown > 0)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine($"注册到{target.IpAddress}:{target.Port}失败......剩余重试次数({countDown})");
                    stringBuilder.AppendLine(ex.Message);
                    Log.Anno(stringBuilder.ToString(), typeof(Register));
                    try
                    {
                        if (_transport.IsOpen)
                        {
                            _transport.Close();
                        }
                        _transport.Dispose();
                    }
                    catch
                    {
                        //忽略异常
                    }
                    --countDown;
                    goto begin;
                }
                else
                {
                    Log.Anno($"{DateTime.Now} 未连接到{target.IpAddress}:{target.Port}注册失败......", typeof(Register));
                }
            }
            finally
            {
                try
                {
                    if (_transport.IsOpen)
                    {
                        _transport.Close();
                    }
                    _transport.Dispose();
                }
                catch
                {
                    //忽略异常
                }
            }
            return(true);
        }