Exemple #1
0
        void connect()
        {
            try
            {
                _ready = false;
                _client?.Dispose();

                findMasterGateway();

                _client = CreateClient(_microServiceHost.MasterGatewayAddress);

                _client.WriteServiceData(new GatewayCommand()
                {
                    Type    = CommandType.RegisterSerivce,
                    Content = new RegisterServiceInfo
                    {
                        ServiceNames = _microServiceHost.ServiceNames.Where(m => m.Value.Enable).Select(m => m.Key).ToArray(),
                        Port         = _microServiceHost.ServicePort,
                        MaxThread    = Environment.ProcessorCount,
                        ServiceId    = _microServiceHost.Id
                    }.ToJsonString()
                });
                var ret = _client.ReadServiceObject <InvokeResult>();
                if (ret.Success == false)
                {
                    _client.Dispose();
                    throw new Exception("网关不允许当前ip作为微服务");
                }

                _ready = true;
                _logger?.LogInformation("和网关连接成功,网关ip:{0} 网关端口:{1}", _microServiceHost.MasterGatewayAddress.Address, _microServiceHost.MasterGatewayAddress.Port);


                //上传已经lock的key
                using (var client = CreateClient(_microServiceHost.MasterGatewayAddress))
                {
                    client.WriteServiceData(new GatewayCommand
                    {
                        Type   = CommandType.UploadLockKeys,
                        Header = new Dictionary <string, string> {
                            { "ServiceId", _microServiceHost.Id }
                        },
                        Content = _keyLocker.GetLockedKeys().ToJsonString()
                    });
                    var cb = client.ReadServiceObject <InvokeResult <string[]> >();
                    if (cb.Data.Length > 0)
                    {
                        _logger?.LogInformation("以下key锁失败,{0}", cb.Data.ToJsonString());
                        foreach (var key in cb.Data)
                        {
                            _keyLocker.RemoveKeyFromLocal(key);
                        }
                    }
                }

                //保持心跳,并且定期发送ClientConnected
                _client.KeepHeartBeating(() => {
                    return(new GatewayCommand
                    {
                        Type = CommandType.ReportClientConnectQuantity,
                        Content = new PerformanceInfo {
                            RequestQuantity = _microServiceHost.ClientConnected,
                            CpuUsage = _cpuInfo.GetCpuUsage()
                        }.ToJsonString()
                    });
                });

                _logger?.LogError("和网关连接断开");
                if (!_manualDisconnected)
                {
                    Thread.Sleep(2000);
                    this.ConnectAsync();
                }
            }
            catch (SocketException)
            {
                if (!_manualDisconnected)
                {
                    Thread.Sleep(2000);
                    this.ConnectAsync();
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, ex.Message);
                if (!_manualDisconnected)
                {
                    Thread.Sleep(2000);
                    this.ConnectAsync();
                }
            }
        }
Exemple #2
0
        void connect()
        {
            try
            {
                _ready = false;
                _client?.Dispose();

                findMasterGateway();

                if (_microServiceHost.SingletonService)
                {
                    try
                    {
                        _client = CreateClient(_microServiceHost.MasterGatewayAddress);
                        _client.WriteServiceData(new GatewayCommand()
                        {
                            Type = CommandType.CheckSupportSingletonService
                        });
                        if (_client.ReadServiceObject <InvokeResult>().Success == false)
                        {
                            throw new Exception("网关不支持SingletonService,请更新网关程序");
                        }
                    }
                    catch
                    {
                        throw new Exception("网关不支持SingletonService,请更新网关程序");
                    }
                    finally
                    {
                        _client.Dispose();
                    }
                }

                _client = CreateClient(_microServiceHost.MasterGatewayAddress);

                _client.WriteServiceData(new GatewayCommand()
                {
                    Type    = CommandType.RegisterSerivce,
                    Content = new RegisterServiceInfo
                    {
                        ServiceNames     = _microServiceHost.ServiceNames.Where(m => m.Value.Enable).Select(m => m.Key).ToArray(),
                        Port             = (_microServiceHost.ServiceAddress == null || _microServiceHost.ServiceAddress.Port == 0) ? _microServiceHost.ServicePort : _microServiceHost.ServiceAddress.Port,
                        ServiceAddress   = _microServiceHost.ServiceAddress == null?null: _microServiceHost.ServiceAddress.Address,
                        MaxThread        = Environment.ProcessorCount,
                        ServiceId        = _microServiceHost.Id,
                        Description      = _microServiceHost.Description,
                        MaxRequestCount  = _microServiceHost.MaxRequestCount,
                        ClientCheckCode  = _microServiceHost.ClientCheckCode,
                        SingletonService = _microServiceHost.SingletonService
                    }.ToJsonString()
                });
                var ret = _client.ReadServiceObject <InvokeResult>();
                if (ret.Success == false)
                {
                    _client.Dispose();
                    _client = null;

                    if (ret.Error == "not allow")
                    {
                        throw new Exception("网关不允许当前ip作为微服务");
                    }
                    else if (ret.Error == "SingletonService")
                    {
                        if (_singletonErrorMsg != null)
                        {
                            _logger?.LogInformation(_singletonErrorMsg);
                            _singletonErrorMsg = null;
                        }
                        Thread.Sleep(1000);
                        this.ConnectAsync();
                        return;
                    }
                    else
                    {
                        throw new Exception("网关不允许连接");
                    }
                }

                _ready = true;
                _logger?.LogInformation("和网关连接成功,网关ip:{0} 网关端口:{1}", _microServiceHost.MasterGatewayAddress.Address, _microServiceHost.MasterGatewayAddress.Port);


                //上传已经lock的key
                using (var client = CreateClient(_microServiceHost.MasterGatewayAddress))
                {
                    client.WriteServiceData(new GatewayCommand
                    {
                        Type   = CommandType.UploadLockKeys,
                        Header = new Dictionary <string, string> {
                            { "ServiceId", _microServiceHost.Id }
                        },
                        Content = _keyLocker.GetLockedKeys().ToJsonString()
                    });
                    var cb = client.ReadServiceObject <InvokeResult <string[]> >();
                    if (cb.Data.Length > 0)
                    {
                        _logger?.LogInformation("以下key锁失败,{0}", cb.Data.ToJsonString());
                        foreach (var key in cb.Data)
                        {
                            _keyLocker.RemoveKeyFromLocal(key);
                        }
                    }
                }

                OnConnectCompleted?.Invoke();

                //保持心跳,并且定期发送ClientConnected
                _client.KeepHeartBeating(() => {
                    return(new GatewayCommand
                    {
                        Type = CommandType.ReportClientConnectQuantity,
                        Content = new PerformanceInfo {
                            RequestQuantity = _microServiceHost.ClientConnected,
                            CpuUsage = _cpuInfo.GetCpuUsage()
                        }.ToJsonString()
                    });
                });
                _client.Dispose();
                _client = null;

                _logger?.LogError("和网关连接断开");
                if (_microServiceHost.AutoExitProcess || _microServiceHost.SingletonService)
                {
                    _logger?.LogInformation("和网关连接断开,准备自动关闭进程");
                    var handler = _microServiceHost.ServiceProvider.GetService <ProcessExitHandler>();
                    if (handler != null)
                    {
                        handler.OnProcessExit();
                    }
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                    return;
                }
                if (!_manualDisconnected)
                {
                    Thread.Sleep(2000);
                    this.ConnectAsync();
                }
            }
            catch (SocketException)
            {
                if (!_manualDisconnected)
                {
                    Thread.Sleep(2000);
                    this.ConnectAsync();
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, ex.Message);
                if (!_manualDisconnected)
                {
                    Thread.Sleep(2000);
                    this.ConnectAsync();
                }
            }
        }