Example #1
0
 public void Log(TraceLevel severity, string className, string message, Exception exception)
 {
     if (exception == null)
     {
         ThriftLog.Info($"Zookeeper {severity.ToString()} {className} {message} ");
     }
     else
     {
         ThriftLog.Info($"Zookeeper {severity.ToString()} {className} {message} {exception.Message} {exception.StackTrace}");
     }
 }
Example #2
0
        public override async Task process(WatchedEvent watchedEvent)
        {
            Console.WriteLine("WatchedEvent:" + watchedEvent.getState().ToString() + ":" + watchedEvent.get_Type().ToString());
            if (watchedEvent.getState() == KeeperState.Expired)
            {
                ThriftLog.Info("重新注册zk");
                await _zk.closeAsync();

                _zk = null;
                Start();
            }
            return;
        }
Example #3
0
        /**
         * 该方法,客户端每调用一次,就会触发一次
         */
        public bool Process(TProtocol iprot, TProtocol oprot)
        {
            TSocket socket = (TSocket)iprot.Transport;

            IPEndPoint ip = (IPEndPoint)socket.TcpClient.Client.RemoteEndPoint;

            if (!IpLimit.AllowConfig(ip.Address.ToString()))
            {
                ThriftLog.Info($"{ip.Address.ToString()} 连接被限制!");
                return(false);
            }

            return(_processor.Process(iprot, oprot));
        }
Example #4
0
 /// <summary>
 ///  注册服务直到成功
 ///  具体RPC服务的注册路径为: /thrift/{namespace}, 该路径上的节点都是永久节点
 ///  RPC服务集群节点的注册路径为: /thrift/{namespace}/ip:port:weight, 末尾的节点是临时节点.
 /// </summary>
 private bool RegeditNode(string zNode, int existsCount)
 {
     try
     {
         var r = _zk.createAsync(zNode, new byte[0] {
         }, _zk_Acl, CreateMode.EPHEMERAL).Result;
         ThriftLog.Info($"{zNode}节点注册完成");
         return(true);
     }
     catch (Exception ex)
     {
         ThriftLog.Info($"{zNode}节点注册失败:" + ex.StackTrace + ex.Message);
         return(false);
     }
 }
Example #5
0
        public static void Stop()
        {
            //先注销zookeeper
            try
            {
                foreach (var server in _services)
                {
                    if (server.Value != null)
                    {
                        server.Value.Logout();
                    }
                }
            }
            catch (Exception ex)
            {
                ThriftLog.Error(ex.Message);
            }

            if (_services.Count > 0)
            {
                int delayedTime = _defaultDelayedTime;
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ThriftServerStopDelayedTime"]))
                {
                    delayedTime = int.Parse(ConfigurationManager.AppSettings["ThriftServerStopDelayedTime"]);
                }

                System.Threading.Thread.Sleep(delayedTime); //延时关闭
            }

            //再关闭服务
            foreach (var server in _services)
            {
                if (server.Key != null)
                {
                    server.Key.Stop();
                }
            }

            _services.Clear();
        }
Example #6
0
        /// <summary>
        /// 创建父结点
        /// </summary>
        private bool CheckNodeParent()
        {
            string[] list = _service.ZookeeperConfig.NodeParent.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < list.Count(); i++)
            {
                string zNode = "";
                for (int j = 0; j <= i; j++)
                {
                    zNode += "/" + list[j];
                }

                try
                {
                    var stat = _zk.existsAsync(zNode).Result;
                    if (stat == null)
                    {
                        if (zNode == "/ThriftServer") //thrift服务的根目录
                        {
                            _zk.createAsync(zNode, new byte[0] {
                            }, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                        }
                        else
                        {
                            _zk.createAsync(zNode, new byte[0] {
                            }, _zk_Acl, CreateMode.PERSISTENT);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ThriftLog.Error("zk:创建父结点异常:" + ex.Message + ex.StackTrace);
                    return(false);
                }
            }
            return(true);
        }
Example #7
0
        private const int _defaultDelayedTime = 20000; //默认延时关闭时间

        public static void Start()
        {
            var _configPath = ConfigurationManager.AppSettings["ThriftServerConfigPath"];

            Config.ThriftConfigSection config = null;
            if (string.IsNullOrEmpty(_configPath))
            {
                config = ConfigurationManager.GetSection("thriftServer") as Config.ThriftConfigSection;
            }
            else
            {
                config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap
                {
                    ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _configPath)
                }, ConfigurationUserLevel.None).GetSection("thriftServer") as Config.ThriftConfigSection;
            }

            if (config == null || config.Services == null)
            {
                throw new Exception("thrift服务配置不存在");
            }

            foreach (Service service in config.Services)
            {
                new System.Threading.Thread(() =>
                {
                    try
                    {
                        Assembly assembly = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, service.HandlerType.Split(',')[1]));
                        object objType    = assembly.CreateInstance(service.HandlerType.Split(',')[0], true);
                        if (objType == null)
                        {
                            throw new Exception(service.HandlerType + "为空");
                        }

                        var handle = TransparentProxy.Create(objType.GetType());

                        string assemblyName = service.SpaceName;
                        //if (!string.IsNullOrEmpty(service.AssemblyName))
                        //    assemblyName = service.AssemblyName;

                        var processor = (Thrift.TProcessor)Type.GetType($"{service.SpaceName}.{service.ClassName}+Processor,{assemblyName}", true)
                                        .GetConstructor(new Type[] { Type.GetType($"{service.SpaceName}.{service.ClassName}+Iface,{assemblyName}", true) })
                                        .Invoke(new object[] { handle });

                        TServerTransport serverTransport = new TServerSocket(service.Port, service.ClientTimeout);

                        TServer server = new TThreadPoolServer(new BaseProcessor(processor, service), serverTransport,
                                                               new TTransportFactory(),
                                                               new TTransportFactory(),
                                                               new TBinaryProtocol.Factory(),
                                                               new TBinaryProtocol.Factory(), service.MinThreadPoolThreads, service.MaxThreadPoolThreads, (x) =>
                        {
                            ThriftLog.Info("log:" + x);
                        });

                        RegeditConfig regiditConfig = null;
                        if (service.ZookeeperConfig != null && service.ZookeeperConfig.Host != "")
                        {
                            regiditConfig = ConfigCenter.RegeditServer(service); //zookeeper 注册服务
                        }
                        ThriftLog.Info($"{service.Name} {service.Port} Starting the TThreadPoolServer...");
                        _services.Add(server, regiditConfig);
                        server.Serve();
                    }
                    catch (Exception ex)
                    {
                        ThriftLog.Error(ex.Message + ex.StackTrace);
                    }
                }).Start();
            }
        }
Example #8
0
        public static void StartMult()
        {
            var _configPath = ConfigurationManager.AppSettings["ThriftServerConfigPath"];

            Config.ThriftConfigSection config = null;
            if (string.IsNullOrEmpty(_configPath))
            {
                config = ConfigurationManager.GetSection("thriftServer") as Config.ThriftConfigSection;
            }
            else
            {
                config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap
                {
                    ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _configPath)
                }, ConfigurationUserLevel.None).GetSection("thriftServer") as Config.ThriftConfigSection;
            }

            if (config == null || config.Services == null)
            {
                throw new Exception("thrift服务配置不存在");
            }

            foreach (Service service in config.Services)
            {
                new System.Threading.Thread(() =>
                {
                    try
                    {
                        TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor();

                        Type[] thriftTypes     = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, service.ThriftAssembly)).GetTypes();
                        Type[] thriftImplTypes = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, service.ThriftImplAssembly)).GetTypes();
                        foreach (var t in thriftTypes)
                        {
                            if (!t.Name.Equals("Iface"))
                            {
                                continue;
                            }
                            string processorFullName = t.FullName.Replace("+Iface", "+Processor");
                            Type processorType       = thriftTypes.FirstOrDefault(c => c.FullName.Equals(processorFullName));
                            object handle            = null;
                            foreach (Type t2 in thriftImplTypes)
                            {
                                if (t2.GetInterfaces().Contains(t))
                                {
                                    handle = TransparentProxy.Create(t2);
                                    break;
                                }
                            }
                            var processor = (Thrift.TProcessor)processorType.GetConstructor(new Type[] { t }).Invoke(new object[] { handle });
                            multiplexedProcessor.RegisterProcessor(t.ReflectedType.Name, processor);
                        }

                        if (service.Port > 0)
                        {
                            if (!PortHelper.PortIsAvailable(service.Port))
                            {
                                throw new Exception("端口冲突");
                            }
                        }
                        else
                        {
                            service.Port = PortHelper.GetFirstAvailablePort();
                            if (service.Port <= 0)
                            {
                                throw new Exception("无端口可用");
                            }
                        }

                        TServerTransport serverTransport = new TServerSocket(service.Port, service.ClientTimeout);

                        TServer server = new TThreadPoolServer(new BaseProcessor(multiplexedProcessor, service), serverTransport,
                                                               new TTransportFactory(),
                                                               new TTransportFactory(),
                                                               new TBinaryProtocol.Factory(),
                                                               new TBinaryProtocol.Factory(), service.MinThreadPoolThreads, service.MaxThreadPoolThreads, (x) =>
                        {
                            ThriftLog.Info("log:" + x);
                        });

                        RegeditConfig regiditConfig = null;
                        if (service.ZookeeperConfig != null && service.ZookeeperConfig.Host != "")
                        {
                            regiditConfig = ConfigCenter.RegeditServer(service); //zookeeper 注册服务
                        }
                        ThriftLog.Info($"{service.Name} {service.Port} Starting the TThreadPoolServer...");
                        _services.Add(server, regiditConfig);
                        server.Serve();
                    }
                    catch (Exception ex)
                    {
                        ThriftLog.Error(ex.Message + ex.StackTrace);
                    }
                }).Start();
            }
        }