Example #1
0
 public void AddMicroService(RegisterServiceInfo service)
 {
     if (_refereeAddress == null)
     {
         return;
     }
     using (NetClient client = new NetClient(_refereeAddress))
     {
         client.WriteServiceData(new GatewayCommand
         {
             Type    = CommandType.RegisterSerivce,
             Content = new RegisterServiceLocation {
                 Host = service.Host,
                 Port = service.Port
             }.ToJsonString()
         });
         var cmd = client.ReadServiceObject <InvokeResult>();
         if (cmd.Success == false)
         {
             throw new Exception("not master");
         }
     }
 }
Example #2
0
        private void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            ProcessExited = true;
            _logger?.LogInformation("准备断开网关");
            try
            {
                var client = new NetClient(_microServiceHost.MasterGatewayAddress);
                client.WriteServiceData(new GatewayCommand {
                    Type    = CommandType.UnRegisterSerivce,
                    Content = _microServiceHost.Id
                });
                client.ReadServiceObject <InvokeResult>();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, ex.Message);
            }

            _logger?.LogInformation("等待事务托管中心事务清零");
            while (_transactionDelegateCenter.List.Count > 0)
            {
                Thread.Sleep(1000);
            }

            _logger?.LogInformation("停止所有定时任务");
            _scheduleTaskManager.StopTasks();

            _logger?.LogInformation("等待客户端请求数清零");
            //等待客户连接处理完毕
            while (_microServiceHost.ClientConnected > 0)
            {
                Thread.Sleep(1000);
            }

            _logger?.LogInformation("客户端请求数为零,当前进程退出");
            Thread.Sleep(1000);
        }
Example #3
0
        public T Invoke <T>(string method, JMSClient tran, params object[] parameters)
        {
            if (tran == null)
            {
                throw new ArgumentNullException("tran");
            }
            this.InvokingInfo.MethodName = method;
            this.InvokingInfo.Parameters = parameters;

            var netclient = NetClientPool.CreateClient(tran.ProxyAddress, this.InvokingInfo.ServiceLocation.Host, this.InvokingInfo.ServiceLocation.Port, tran.ServiceClientCertificate);

            try
            {
                var cmd = new InvokeCommand()
                {
                    Header     = tran.GetCommandHeader(),
                    Service    = this.InvokingInfo.ServiceName,
                    Method     = method,
                    Parameters = parameters.Length == 0 ? null :
                                 parameters.GetStringArrayParameters()
                };


                netclient.WriteServiceData(cmd);
                var result = netclient.ReadServiceObject <InvokeResult <T> >();
                if (result.Success == false)
                {
                    throw new RemoteException(tran.TransactionId, result.Error);
                }
                NetClient = netclient;

                if (result.SupportTransaction)
                {
                    tran.AddConnect(this);
                }
                else
                {
                    NetClientPool.AddClientToPool(netclient);
                }

                return(result.Data);
            }
            catch (ConvertException ex)
            {
                InvokeResult <string> otherObj = null;
                try
                {
                    otherObj = ex.Source.FromJson <InvokeResult <string> >();
                }
                catch
                {
                }

                if (otherObj != null)
                {
                    throw new ConvertException(otherObj.Data, $"无法将{otherObj.Data}实例化为{typeof(T).FullName}");
                }

                throw ex;
            }
            catch (Exception)
            {
                netclient.Dispose();
                throw;
            }
        }
Example #4
0
 public void ReConnect(JMSClient tran)
 {
     ReConnectCount++;
     NetClient = NetClientPool.CreateClient(tran.ProxyAddress, this.InvokingInfo.ServiceLocation.Host, this.InvokingInfo.ServiceLocation.Port, tran.ServiceClientCertificate);
 }
Example #5
0
 public void ReConnect(IRemoteClient tran)
 {
     ReConnectCount++;
     NetClient             = NetClientPool.CreateClient(tran.ProxyAddress, this.InvokingInfo.ServiceLocation.ServiceAddress, this.InvokingInfo.ServiceLocation.Port, tran.ServiceClientCertificate);
     NetClient.ReadTimeout = tran.Timeout;
 }
Example #6
0
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    NetClient client = new NetClient("127.0.0.1", 8911);
                    client.Dispose();
                    break;
                }
                catch (Exception)
                {
                    Thread.Sleep(100);
                }
            }


            ServiceCollection services = new ServiceCollection();

            var gateways = new NetAddress[] {
                new NetAddress {
                    Address = "localhost",
                    Port    = 8911
                }
            };
            var msp = new MicroServiceHost(services);


            var builder = new ConfigurationBuilder();

            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
            var configuration = builder.Build();

            //services.UseJmsTokenAuthentication(AuthorizationContentType.String, "127.0.0.1", 9911,"auth");
            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(configuration.GetSection("Logging"));
                loggingBuilder.AddConsole(); // 将日志输出到控制台
            });
            services.AddSingleton <IConfiguration>(configuration);


            msp.ClientCheckCode = @"
            try
            {
               var number = Convert.ToInt64(arg);
                return number > 0;
            }
            catch 
            {
            }
            return false;

";

            msp.Register <Controller1>("Controller1");
            msp.Register <Controller2>("Service2");
            msp.RegisterScheduleTask <AutoRun1>();
            msp.ServiceProviderBuilded += Msp_ServiceProviderBuilded;
            msp.Build(8912, gateways)
            .Run();
        }
        public void Handle(NetClient client, GatewayCommand cmd)
        {
            try
            {
                _listeningFiles = cmd.Content.FromJson <string[]>();

                while (true)
                {
                    if (_changedFiles.Count == 0)
                    {
                        client.WriteServiceData(new InvokeResult
                        {
                            Success = true
                        });
                        client.ReadServiceObject <InvokeResult>();
                    }
                    else
                    {
                        string[] sendFiles = null;
                        lock (_changedFiles)
                        {
                            sendFiles = _changedFiles.ToArray();
                            _changedFiles.Clear();
                        }

                        foreach (var file in sendFiles)
                        {
                            string fullpath = $"{_root}/{file}";
                            if (File.Exists(fullpath))
                            {
                                byte[] data = null;
                                try
                                {
                                    data = File.ReadAllBytes(fullpath);
                                }
                                catch (Exception ex)
                                {
                                    _logger?.LogError(ex, ex.Message);
                                    continue;
                                }

                                client.WriteServiceData(new InvokeResult
                                {
                                    Success = true,
                                    Data    = file
                                });

                                client.Write(data.Length);
                                client.Write(data);
                                client.ReadServiceObject <InvokeResult>();
                            }
                        }
                    }


                    _waitObj.WaitOne(38000);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                SystemEventCenter.ShareFileChanged -= SystemEventCenter_ShareFileChanged;
            }
        }
Example #8
0
        void toBeMaster()
        {
            /*
             * 申请成为master -->
             *      成为master     --> 维持心跳          --> 心跳断开后 -->重新连接裁判机申请成为master
             *                                                                                          -->还是master ...
             *                                                                                          -->如果不再是master --> 断开连接的所有微服务
             *      不能成为master --> 和master维持心跳  --> 心跳断开后 -->重新连接裁判机申请成为master
             */


            NetAddress masterAddr = null;

            while (true)
            {
                try
                {
                    if (!this.IsMaster)
                    {
                        _lockKeyManager.IsReady = false;
                    }

                    using (var client = new NetClient(_refereeAddress))
                    {
                        client.WriteServiceData(new GatewayCommand {
                            Type    = CommandType.ApplyToBeMaster,
                            Content = _gateway.Port.ToString()
                        });
                        var ret = client.ReadServiceObject <InvokeResult <string> >();

                        _logger?.LogInformation("与裁判连接成功,裁判返回数据:{0}", ret.Data);
                        if (ret.Success)
                        {
                            masterAddr = null;
                            if (this.IsMaster == false)
                            {
                                _logger?.LogInformation("成为主网关");
                                _waitServiceList = ret.Data.FromJson <ConcurrentDictionary <string, RegisterServiceLocation> >();
                                this.IsMaster    = true;

                                //等待所有微服务上传locked key
                                var timeout = _lockKeyManager.KeyTimeout / 1000;
                                for (int i = 0; i < timeout && _waitServiceList.Count > 0; i++)
                                {
                                    _logger?.LogInformation("还有{0}个微服务没有报到 {1}", _waitServiceList.Count, _waitServiceList.Keys.ToArray().ToJsonString());
                                    Thread.Sleep(1000);
                                }
                                _lockKeyManager.IsReady = true;

                                if (_waitServiceList.Count > 0)
                                {
                                    _logger?.LogInformation("还有{0}个微服务没有报到,但被忽略了。", _waitServiceList.Count);
                                }
                                _logger?.LogInformation("lockKeyManager就绪");
                                _logger?.LogDebug("锁记录:{0}", _lockKeyManager.GetCaches().ToJsonString());
                            }

                            client.KeepHeartBeating();
                            _logger?.LogInformation("与裁判的连接断开");
                        }
                        else
                        {
                            if (this.IsMaster)
                            {
                                this.IsMaster           = false;
                                _lockKeyManager.IsReady = false;
                                //不是主网关,需要断开所有微服务
                                var allservices = _gateway.OnlineMicroServices.ToArray();
                                foreach (var s in allservices)
                                {
                                    s.Close();
                                }
                            }
                            //另一个网关成为主网关
                            masterAddr = ret.Data.FromJson <NetAddress>();
                        }
                    }

                    if (masterAddr != null)
                    {
                        _logger?.LogInformation("准备和主网关连接{0}", masterAddr.ToJsonString());
                        //连上主网关,直到连接出现问题,再申请成为主网关
                        using (var client = new NetClient(masterAddr))
                        {
                            _logger?.LogInformation("与主网关连接心跳");
                            client.KeepHeartBeating();
                            Thread.Sleep(100);
                            _logger?.LogInformation("与主网关连接断开");
                        }
                    }
                }
                catch (SocketException)
                {
                    Thread.Sleep(2000);
                }
                catch (Exception ex)
                {
                    Thread.Sleep(2000);
                    _logger?.LogError(ex, ex.Message);
                }
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    NetClient client = new NetClient("127.0.0.1", 8911);
                    client.Dispose();
                    break;
                }
                catch (Exception)
                {
                    Thread.Sleep(100);
                }
            }

            var gatewaycert = new System.Security.Cryptography.X509Certificates.X509Certificate2("../../../../pfx/client.pfx", "123456");

            ServiceCollection services = new ServiceCollection();

            var gateways = new NetAddress[] {
                new NetAddress {
                    Address = "localhost",
                    Port    = 8911
                }
            };
            var msp = new MicroServiceHost(services);

            if (File.Exists("./appsettings.json") == false)
            {
                //本地没有appsettings.json,先从网关拉一个
                msp.GetGatewayShareFile(gateways[0], "test/appsettings.json", "./appsettings.json", gatewaycert);
            }


            var builder = new ConfigurationBuilder();

            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
            var configuration = builder.Build();


            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(configuration.GetSection("Logging"));
                loggingBuilder.AddConsole(); // 将日志输出到控制台
            });
            services.AddSingleton <IConfiguration>(configuration);

            msp.MapShareFileToLocal(gateways[0], "test/appsettings.json", "./appsettings.json", (p, p2) => {
                Console.WriteLine(p + "回调");
            });
            msp.MapShareFileToLocal(gateways[0], "test/appsettings2.json", "./appsettings2.json");


            msp.Register <Controller1>("Controller1");
            msp.Register <Controller2>("Service2");
            msp.RegisterScheduleTask <AutoRun>();
            msp.Build(8912, gateways)
            .UseSSL(c =>
            {     //配置ssl
                c.GatewayClientCertificate = gatewaycert;
                c.ServerCertificate        = new X509Certificate2("../../../../pfx/service_server.pfx", "123456");
            })
            .Run();
        }