コード例 #1
0
        public IRedisClientsManager GetRedisClientsManager(int millisecondsTimeout)
        {
            if (millisecondsTimeout <= 0)
            {
                return(_redisSentinel.Start());
            }

            var clientsManager = ConnectionUtil.Connect(() => _redisSentinel.Start(), millisecondsTimeout, _logger);

            return(clientsManager);
        }
コード例 #2
0
        public void Execute()
        {
            var sentinelHosts = new[] { "127.0.0.1:26380", "127.0.0.1:26381", "127.0.0.1:26382" };
            var sentinel      = new RedisSentinel(sentinelHosts, masterName: "mymaster");

            sentinel.HostFilter = host => "password@{0}".Fmt(host);
            var manager = sentinel.Start();

            sentinel.OnWorkerError = exception => Console.WriteLine(exception);

            while (true)
            {
                try
                {
                    const string RedisKey = "my Name";
                    using (var client = manager.GetClient())
                    {
                        var result = client.Get <string>(RedisKey);
                        Console.WriteLine("Redis Key: {0} \t Port: {1}", result, client.Port);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error {0}".Fmt(ex.Message));
                }
                Thread.Sleep(3000);
            }
        }
コード例 #3
0
        private void Connect()
        {
            if (_sentinel != null)
            {
                return;
            }

            _connectionLock.Wait();
            try {
                if (_sentinel == null)
                {
                    // sentinel settings
                    _sentinel = new RedisSentinel(_options.Hosts, _options.MasterGroup)
                    {
                        ScanForOtherSentinels = _options.ScanForOtherSentinels,
                        RedisManagerFactory   = (master, slaves) => new RedisManagerPool(master),
                        // set the client connection string
                        HostFilter = host => {
                            var h = String.Empty;
                            h += String.IsNullOrWhiteSpace(_options.AuthPass) ? "" : $"{_options.AuthPass}@";
                            h += $"{host}?db=1&RetryTimeout=5000";
                            return(h);
                        },
                    };

                    // start monitoring
                    _manager = _sentinel.Start();
                }
            } finally {
                _connectionLock.Release();
            }
        }
コード例 #4
0
        public void Execute()
        {
            string AddPassword(string host) => $"password@{host}";

            var sentinelHosts = new[] { "127.0.0.1:26380", "127.0.0.1:26381", "127.0.0.1:26382" };
            var sentinel      = new RedisSentinel(sentinelHosts.Map(AddPassword), masterName: "mymaster")
            {
                HostFilter         = AddPassword,
                SentinelHostFilter = AddPassword,
            };
            var manager = sentinel.Start();

            sentinel.OnWorkerError = Console.WriteLine;

            while (true)
            {
                try
                {
                    const string RedisKey = "my Name";
                    using var client = manager.GetClient();
                    var result = client.Get <string>(RedisKey);
                    Console.WriteLine("Redis Key: {0} \t Port: {1}", result, client.Port);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error {0}".Fmt(ex.Message));
                }
                Thread.Sleep(3000);
            }
        }
コード例 #5
0
ファイル: RedisSentinelTests.cs プロジェクト: yudiefly/Shadow
        public void Can_Connect_Sentinel_Test()
        {
            var sentinelHosts = new string[]
            {
                "10.110.76.178:26379",
            };

            var sentinel = new RedisSentinel(sentinelHosts, "host6379")
            {
                OnFailover = manager =>
                {
                    "Redis Managers were Failed Over to new hosts".Print();
                },
                OnWorkerError = ex =>
                {
                    "Worker error: {0}".Print(ex);
                },
                OnSentinelMessageReceived = (channel, msg) =>
                {
                    "Received '{0}' on channel '{1}' from Sentinel".Print(channel, msg);
                },

                //HostFilter = host => $"redis123456@{host}"
                HostFilter = host => $"{host}?password=redis123456",
            };

            var redisManager = sentinel.Start();         // 尝试与哨兵服务器进行通信(检查服务器是否可用)
            var redisClient  = redisManager.GetClient(); // 尝试连接服务器
            var foo2         = redisClient.Get <string>("foo2");

            redisClient.Dispose();

            Assert.True(foo2 == "f2");
        }
コード例 #6
0
ファイル: RedisFeature.cs プロジェクト: hoaihuongbk/agency
        public void Register(IAppHost appHost)
        {
            var container   = appHost.GetContainer();
            var appSettings = appHost.AppSettings;
            var connections = appSettings.Get <Dictionary <string, string> >("connectionStrings");

#if DEBUG
            var sentinelHosts = new[] { connections.GetValueOrDefault("Sentinel0"), connections.GetValueOrDefault("Sentinel1"), connections.GetValueOrDefault("Sentinel2") };
            var sentinel      = new RedisSentinel(sentinelHosts, masterName: appSettings.GetString("redis.mastername"))
            {
                RedisManagerFactory = (master, slaves) => new RedisManagerPool(master, new RedisPoolConfig()
                {
                    MaxPoolSize = 20
                }),
                HostFilter = host => "{0}?db=0".Fmt(host)
            };
            container.Register <IRedisClientsManager>(c => sentinel.Start());
#else
            var redisManager = new RedisManagerPool(connections.GetValueOrDefault("Sentinel0"), new RedisPoolConfig()
            {
                MaxPoolSize = 20,
            });
            container.Register <IRedisClientsManager>(c => redisManager);
#endif
        }
コード例 #7
0
        public void Can_connect_to_GoogleCloud_3SentinelSetup()
        {
            var sentinel = new RedisSentinel(GoogleCloudSentinelHosts, masterName: "master")
            {
                IpAddressMap = {
                    {"10.240.34.152", "146.148.77.31"},
                    {"10.240.203.193","130.211.139.141"},
                    {"10.240.209.52", "107.178.218.53"},
                }
            };

            var redisManager = sentinel.Start();

            using (var client = redisManager.GetClient())
            {
                "{0}:{1}".Print(client.Host, client.Port);

                client.FlushAll();

                client.SetEntry("Sentinel3Setup", "GoogleCloud");

                var result = client.GetEntry("Sentinel3Setup");
                Assert.That(result, Is.EqualTo("GoogleCloud"));
            }

            using (var readOnly = redisManager.GetReadOnlyClient())
            {
                "{0}:{1}".Print(readOnly.Host, readOnly.Port);

                var result = readOnly.GetEntry("Sentinel3Setup");
                Assert.That(result, Is.EqualTo("GoogleCloud"));
            }
        }
コード例 #8
0
        internal static IRedisClientsManager InitRedisClientManager(string clusterName, string clusterNodes,
                                                                    string redisConnectionString)
        {
            lock (SyncObj)
            {
                if (_redisClientsManager == null)
                {
                    if (string.IsNullOrWhiteSpace(clusterName) ||
                        string.IsNullOrWhiteSpace(clusterNodes))
                    {
                        _redisClientsManager = new RedisManagerPool(redisConnectionString);
                    }
                    else
                    {
                        var sentinelHosts = clusterNodes.Split(',');

                        var sentinel = new RedisSentinel(sentinelHosts, clusterName);
                        sentinel.HostFilter          = host => redisConnectionString.Fmt(host);
                        sentinel.RedisManagerFactory =
                            (master, slaves) => new PooledRedisClientManager(master, slaves);

                        _redisClientsManager = sentinel.Start();
                    }
                }
            }

            return(_redisClientsManager);
        }
コード例 #9
0
        private async Task ConnectAsync(CancellationToken token = default(CancellationToken))
        {
            token.ThrowIfCancellationRequested();

            if (_sentinel != null)
            {
                return;
            }

            await _connectionLock.WaitAsync(token);

            try {
                if (_sentinel == null)
                {
                    // sentinel settings
                    _sentinel = new RedisSentinel(_options.Hosts, _options.MasterGroup)
                    {
                        ScanForOtherSentinels = _options.ScanForOtherSentinels,
                        RedisManagerFactory   = (master, slaves) => new RedisManagerPool(master),
                        // set the client connection string
                        HostFilter = host => {
                            var h = String.Empty;
                            h += String.IsNullOrWhiteSpace(_options.AuthPass) ? "" : $"{_options.AuthPass}@";
                            h += $"{host}?db=1&RetryTimeout=5000";
                            return(h);
                        },
                    };

                    // start monitoring
                    _manager = await Task.Run(() => _sentinel.Start()).ConfigureAwait(false);
                }
            } finally {
                _connectionLock.Release();
            }
        }
コード例 #10
0
    /// <summary>
    /// 创建 Redis 连接池管理对象。
    /// </summary>
    private static void CreateManager()
    {
        string[] sentinelServerHosts = SplitServerHosts(_redisConfiguration.SentinelServerHosts, ",");
        var      redisSentinel       = new RedisSentinel(sentinelServerHosts, _redisConfiguration.MasterName);

        _redisClientsManager = redisSentinel.Start();
    }
コード例 #11
0
 public void Can_Get_Redis_ClientsManager()
 {
     using (var sentinel = new RedisSentinel(Config.SentinelHosts, Config.SentinelMasterName)) {
         var clientsManager = sentinel.Start();
         using (var client = clientsManager.GetClient()) {
             Assert.That(client.GetHostString(), Is.EqualTo(Config.Sentinel6380));
         }
     }
 }
コード例 #12
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        public override void Configure(Container container)
        {
            var appSettings = new AppSettings();

            JsConfig.EmitCamelCaseNames      = true;
            JsConfig <DateTime> .SerializeFn = dateObj => string.Format("{0:yyyy-MM-ddTHH:mm:ss.000}", dateObj);
            JsConfig <TimeSpan> .SerializeFn = timeSpan => string.Format("{0:00}:{1:00}", timeSpan.Hours, timeSpan.Minutes);
            JsConfig <DBNull> .SerializeFn   = dbNull => string.Empty;


#if DEBUG
            var sentinelHosts = new[] { ConfigUtils.GetConnectionString("Sentinel0"), ConfigUtils.GetConnectionString("Sentinel1"), ConfigUtils.GetConnectionString("Sentinel2") };
            var sentinel      = new RedisSentinel(sentinelHosts, masterName: "mymaster");
            sentinel.RedisManagerFactory = (master, slaves) => new RedisManagerPool(master, new RedisPoolConfig()
            {
                MaxPoolSize = 20
            });
            sentinel.HostFilter = host => "{0}?db=0".Fmt(host);
            container.Register <IRedisClientsManager>(c => sentinel.Start());
#else
            var redisManager = new RedisManagerPool(ConfigUtils.GetConnectionString("Sentinel0"), new RedisPoolConfig()
            {
                MaxPoolSize = 20,
            });
            container.Register <IRedisClientsManager>(c => redisManager);
#endif


            //Configuring
            ConfigureDb(container, appSettings);
            ConfigureLogging(container, appSettings);
            ConfigureAuth(container, appSettings);
            ConfigureFilter(container, appSettings);
            ConfigureValidation(container, appSettings);
            ConfigureExceptionFormat(container, appSettings);
            ConfigureConverter(container, appSettings);
            //ConfigureGateway(container, appSettings);

            SetConfig(new HostConfig
            {
                HandlerFactoryPath = "api",
                //EnableFeatures = Feature.All.Remove(disableFeatures), //all formats except of JSV and SOAP
                DebugMode                  = true,           //Show StackTraces in service responses during development
                WriteErrorsToResponse      = false,          //Disable exception handling
                DefaultContentType         = MimeTypes.Json, //Change default content type
                AllowJsonpRequests         = true,           //Enable JSONP requests
                RestrictAllCookiesToDomain = appSettings.GetString("rootDomain")
            });

            //Plugins
            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature());
            Plugins.Add(new ValidationFeature());

            Plugins.Add(new CommonFeature());
        }
コード例 #13
0
        public void Can_specify_db_on_RedisSentinel()
        {
            using (var sentinel = new RedisSentinel(Config.SentinelHosts, Config.SentinelMasterName)) {
                sentinel.HostFilter = host => string.Format("{0}?db=1", host);

                using (var clientsManager = sentinel.Start()) {
                    using (var client = clientsManager.GetClient()) {
                        Assert.That(client.Db, Is.EqualTo(1));
                    }
                }
            }
        }
コード例 #14
0
        public void Run_sentinel_for_10_minutes()
        {
            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            var sentinelHost = "{0}:{1}".Fmt(TestConfig.SentinelHost, TestConfig.RedisSentinelPort);
            var sentinel     = new RedisSentinel(sentinelHost, TestConfig.MasterName)
            {
                OnFailover = manager =>
                {
                    "Redis Managers Failed Over to new hosts".Print();
                },
                OnWorkerError = ex =>
                {
                    "Worker error: {0}".Print(ex);
                },
                OnSentinelMessageReceived = (channel, msg) =>
                {
                    "Received '{0}' on channel '{1}' from Sentinel".Print(channel, msg);
                },
            };

            var redisManager = sentinel.Start();

            var aTimer = new Timer
            {
                Interval = 1000,
                Enabled  = true
            };

            aTimer.Elapsed += (sender, args) =>
            {
                "Incrementing key".Print();

                string key = null;
                using (var redis = redisManager.GetClient())
                {
                    var counter = redis.Increment("key", 1);
                    key = "key" + counter;
                    "Set key {0} in read/write client".Print(key);
                    redis.SetEntry(key, "value" + 1);
                }

                using (var redis = redisManager.GetClient())
                {
                    "Get key {0} in read-only client...".Print(key);
                    var value = redis.GetEntry(key);
                    "{0} = {1}".Print(key, value);
                }
            };

            Thread.Sleep(TimeSpan.FromMinutes(10));
        }
コード例 #15
0
        public void Does_scan_for_other_active_sentinels()
        {
            using var sentinel = new RedisSentinel(SentinelHosts[0])
                  {
                      ScanForOtherSentinels = true
                  };
            var clientsManager = sentinel.Start();

            Assert.That(sentinel.SentinelHosts, Is.EquivalentTo(SentinelHosts));

            using var client = clientsManager.GetClient();
            Assert.That(client.GetHostString(), Is.EqualTo(MasterHosts[0]));
        }
コード例 #16
0
        public void Can_Get_Redis_ClientsManager()
        {
            var sentinel = new RedisSentinel(new[] { "{0}:{1}".Fmt(TestConfig.SentinelHost, TestConfig.RedisSentinelPort) }, TestConfig.MasterName);

            var clientsManager = sentinel.Start();
            var client         = clientsManager.GetClient();

            Assert.That(client.Host, Is.EqualTo("127.0.0.1").Or.EqualTo(TestConfig.SentinelHost));
            Assert.AreEqual(client.Port, TestConfig.RedisPort);

            client.Dispose();
            sentinel.Dispose();
        }
コード例 #17
0
        public void Can_specify_db_on_RedisSentinel()
        {
            var sentinelHosts = new[] { "{0}:{1}".Fmt(TestConfig.SentinelHost, TestConfig.RedisSentinelPort) };
            var sentinel      = new RedisSentinel(sentinelHosts, TestConfig.MasterName)
            {
                HostFilter = host => "{0}?db=1".Fmt(host)
            };

            using (var clientsManager = sentinel.Start())
                using (var client = clientsManager.GetClient())
                {
                    Assert.That(client.Db, Is.EqualTo(1));
                }
        }
コード例 #18
0
        public void Does_scan_for_other_active_sentinels()
        {
            using (var sentinel = new RedisSentinel(Config.Sentinel26380)
            {
                ScanForOtherSentinels = true
            }) {
                var clientsManager = sentinel.Start();

                Assert.That(sentinel.SentinelHosts, Is.EquivalentTo(Config.SentinelHosts));

                using (var client = clientsManager.GetClient()) {
                    Assert.That(client.GetHostString(), Is.EqualTo(Config.Sentinel6380));
                }
            }
        }
コード例 #19
0
        public void Can_connect_to_3SentinelSetup()
        {
            var sentinel = new RedisSentinel(SentinelHosts);

            var redisManager = sentinel.Start();

            using (var client = redisManager.GetClient())
            {
                client.FlushAll();

                client.SetEntry("Sentinel3Setup", "IntranetSentinel");

                var result = client.GetEntry("Sentinel3Setup");
                Assert.That(result, Is.EqualTo("IntranetSentinel"));
            }
        }
コード例 #20
0
        public void Can_specify_Timeout_on_RedisManager()
        {
            using (var sentinel = new RedisSentinel(Config.SentinelHosts, Config.SentinelMasterName)) {
                sentinel.RedisManagerFactory = (masters, slaves) => new PooledRedisClientManager(masters, slaves)
                {
                    IdleTimeoutSecs = 20
                };

                using (var clientsManager = (PooledRedisClientManager)sentinel.Start()) {
                    using (var client = clientsManager.GetClient()) {
                        Assert.That(clientsManager.IdleTimeoutSecs, Is.EqualTo(20));
                        Assert.That(((RedisNativeClient)client).IdleTimeoutSecs, Is.EqualTo(20));
                    }
                }
            }
        }
コード例 #21
0
        public void Can_connect_to_3SentinelSetup()
        {
            var sentinel = new RedisSentinel(SentinelHosts);

            var redisManager = sentinel.Start();

            using (var client = redisManager.GetClient())
            {
                client.FlushAll();

                client.SetValue("Sentinel3Setup", "IntranetSentinel");

                var result = client.GetValue("Sentinel3Setup");
                Assert.That(result, Is.EqualTo("IntranetSentinel"));
            }
        }
コード例 #22
0
        private static IRedisClientsManager GetRedisClientsManager()
        {
            //var sentinelHosts = new[] { "somredis01.zerochaos.local:26379","somredis02.zerochaos.local:26379","somredis03.zerochaos.local:26379" };
            var sentinelHosts = new[] { "supdevredis01.zcdev.local:26379", "supdevredis01.zcdev.local:26380", "supdevredis01.zcdev.local:26381" };
            //var sentinelHosts = new[] { "supredis01.zcdev.local:26379", "supredis01.zcdev.local:26380", "supredis01.zcdev.local:26381" };
            var sentinel = new RedisSentinel(sentinelHosts, masterName: "zcredismaster");

            if (redisManager != null)
            {
                return(redisManager);
            }
            else
            {
                // By default RedisSentinel uses a PooledRedisClientManager
                return(sentinel.Start());
            }
        }
コード例 #23
0
        public void Can_connect_to_RedisSentinel()
        {
            RedisConfig.AssumeServerVersion = 4000;

            var sentinel = new RedisSentinel("52.7.181.87:26379")
            {
                IpAddressMap =
                {
                    { "127.0.0.1", "52.7.181.87" }
                }
            };

            var redisManager = sentinel.Start();

            using (var client = redisManager.GetClient())
            {
                Assert.That(client.Ping());
            }
        }
コード例 #24
0
        public void Execute()
        {
            RedisConfig.DisableVerboseLogging = true;

            var sentinel = new RedisSentinel(Config.SentinelHosts, Config.SentinelMasterName);

            var redisManager = sentinel.Start();

            using (var client = redisManager.GetClient()) {
                client.FlushAll();
            }

            using (var client = redisManager.GetClient()) {
                Console.WriteLine(client.IncrementValue("counter").ToString());
            }

            Console.WriteLine("Force 'SENTINEL failover mymaster'...");

            try {
                using (var client = redisManager.GetClient()) {
                    Console.WriteLine(client.IncrementValue("counter").ToString());
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            try {
                using (var client = redisManager.GetClient()) {
                    Console.WriteLine(client.IncrementValue("counter").ToString());
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            try {
                using (var client = redisManager.GetClient()) {
                    Console.WriteLine(client.IncrementValue("counter").ToString());
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #25
0
        public void Can_specify_Timeout_on_RedisManager()
        {
            var sentinel = new RedisSentinel(new[] { "{0}:{1}".Fmt(TestConfig.SentinelHost, TestConfig.RedisSentinelPort) }, TestConfig.MasterName)
            {
                RedisManagerFactory =
                {
                    OnInit                                            = r =>
                    {
                        ((PooledRedisClientManager)r).IdleTimeOutSecs = 20;
                    }
                }
            };

            using (var clientsManager = (PooledRedisClientManager)sentinel.Start())
                using (var client = clientsManager.GetClient())
                {
                    Assert.That(clientsManager.IdleTimeOutSecs, Is.EqualTo(20));
                    Assert.That(((RedisNativeClient)client).IdleTimeOutSecs, Is.EqualTo(20));
                }
        }
コード例 #26
0
        public void Run_sentinel_for_10_minutes()
        {
            using (var sentinel = new RedisSentinel(Config.SentinelHosts, Config.SentinelMasterName)) {
                sentinel.OnFailover = manager => {
                    Console.WriteLine("Redis Managers Failed Over to new hosts");
                };
                sentinel.OnWorkerError = ex => {
                    Console.WriteLine("Worker error: {0}", ex);
                };
                sentinel.OnSentinelMessageReceived = (channel, msg) => {
                    Console.WriteLine("Received '{0}' on channel '{1}' from Sentinel", channel, msg);
                };

                using (var redisManager = sentinel.Start()) {
                    void TimerCallback(object state)
                    {
                        Console.WriteLine("Incrementing key");

                        string key = null;

                        using (var redis = redisManager.GetClient()) {
                            var counter = redis.Increment("key", 1);
                            key = "key" + counter;
                            Console.WriteLine("Set key {0} in read/write client", key);
                            redis.SetValue(key, "value" + 1);
                        }

                        using (var redis = redisManager.GetClient()) {
                            Console.WriteLine("Get key {0} in read-only client...", key);
                            var value = redis.GetValue(key);
                            Console.WriteLine("{0} = {1}", key, value);
                        }
                    }

                    var aTimer = new Timer(TimerCallback, null, 0, 1000);
                }
            }

            Thread.Sleep(TimeSpan.FromMinutes(10));
        }
コード例 #27
0
 public IRedisClient GetClient()
 {
     try
     {
         RedisSentinel redisSentinel = new RedisSentinel(
             JsonConfig.Value.Redis.SentinelPattern.SentinelHosts.Split(',').ToList(), // MinecraftConfiguration.Minecraft_Redis_SentinelHosts,
             JsonConfig.Value.Redis.SentinelPattern.MasterName                         //    MinecraftConfiguration.Minecraft_Redis_SentinelPattern_MasterName
             );
         var manager = redisSentinel.Start() as PooledRedisClientManager;
         var client  = manager.GetClient();
         return(client);
     }
     catch (TimeoutException ex)
     {
         Console.WriteLine("连接超时  " + ex.ToString());
         return(null);
     }
     catch (Exception ex)
     {
         Console.WriteLine("异常  " + ex.ToString());
         return(null);
     }
 }
コード例 #28
0
        public void Can_connect_to_3SentinelSetup()
        {
            var sentinel = new RedisSentinel(Config.SentinelHosts, Config.SentinelMasterName);

            var redisManager = sentinel.Start();

            using (var client = redisManager.GetClient()) {
                Console.WriteLine("{0}:{1}", client.Host, client.Port);

                client.FlushAll();

                client.SetValue("Sentinel3Setup", "IntranetSentinel");

                var result = client.GetValue("Sentinel3Setup");
                Assert.That(result, Is.EqualTo("IntranetSentinel"));
            }

            using (var readOnly = redisManager.GetReadOnlyClient()) {
                Console.WriteLine("{0}:{1}", readOnly.Host, readOnly.Port);

                var result = readOnly.GetValue("Sentinel3Setup");
                Assert.That(result, Is.EqualTo("IntranetSentinel"));
            }
        }
コード例 #29
0
        public void Execute()
        {
            var sentinel = new RedisSentinel(Config.SentinelHosts, Config.SentinelMasterName);

            sentinel.HostFilter = host => string.Format("password@{0}", host);
            var manager = sentinel.Start();

            sentinel.OnWorkerError = Console.WriteLine;

            while (true)
            {
                try {
                    const string redisKey = "my Name";
                    using (var client = manager.GetClient()) {
                        var result = client.Get <string>(redisKey);
                        Console.WriteLine("Redis Key: {0} \t Port: {1}", result, client.Port);
                    }
                } catch (Exception ex) {
                    Console.WriteLine("Error {0}", ex.Message);
                }

                Thread.Sleep(3000);
            }
        }
コード例 #30
0
        /// <summary>
        /// Init
        /// </summary>
        public static void Init()
        {
            JsConfig.DateHandler    = DateHandler.ISO8601DateTime;
            JsConfig.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            RedisConfigurationSection redisSection = ConfigurationManager.GetSection("redis") as RedisConfigurationSection;

            IsKeepAliveMode = redisSection.IsKeepAlive;
            IsSentinelMode  = redisSection.IsSentinel;

            if (IsKeepAliveMode)
            {
                KeepAliveService.Instance.Init();
            }

            if (!IsSentinelMode)
            {
                string[] arrRW = redisSection.ReadWriteHosts.Split(',').Select(x => x.Trim()).ToArray();
                string[] arrR  = redisSection.ReadOnlyHosts.Split(',').Select(x => x.Trim()).ToArray();

                Prcm = new PooledRedisClientManager(arrRW, arrR, new RedisClientManagerConfig
                {
                    MaxWritePoolSize = redisSection.MaxWritePoolSize,
                    MaxReadPoolSize  = redisSection.MaxReadPoolSize,
                    AutoStart        = redisSection.AutoStart
                });
            }
            else
            {
                SentinelNodePwd = redisSection.SentinelNodePwd;

                var           ls = redisSection.SentinelHosts.Split(',').Select(x => x.Trim()).ToList();
                RedisSentinel rs = new RedisSentinel(ls);
                Rcm = rs.Start();
            }
        }
コード例 #31
0
        public void Run_sentinel_for_10_minutes()
        {
            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled:true);

            var sentinelHost = "{0}:{1}".Fmt(TestConfig.SentinelHost, TestConfig.RedisSentinelPort);
            var sentinel = new RedisSentinel(sentinelHost, TestConfig.MasterName)
            {
                OnFailover = manager => 
                {
                    "Redis Managers Failed Over to new hosts".Print();
                },
                OnWorkerError = ex =>
                {
                    "Worker error: {0}".Print(ex);
                },
                OnSentinelMessageReceived = (channel, msg) =>
                {
                    "Received '{0}' on channel '{1}' from Sentinel".Print(channel, msg);
                },                
            };

            var redisManager = sentinel.Start();

            var aTimer = new Timer
            {
                Interval = 1000, 
                Enabled = true
            };
            aTimer.Elapsed += (sender, args) => 
            {
                "Incrementing key".Print();

                string key = null;
                using (var redis = redisManager.GetClient())
                {
                    var counter = redis.Increment("key", 1);
                    key = "key" + counter;
                    "Set key {0} in read/write client".Print(key);
                    redis.SetEntry(key, "value" + 1);
                }

                using (var redis = redisManager.GetClient())
                {
                    "Get key {0} in read-only client...".Print(key);
                    var value = redis.GetEntry(key);
                    "{0} = {1}".Print(key, value);
                }
            };

            Thread.Sleep(TimeSpan.FromMinutes(10));
        }
コード例 #32
0
        public void Execute()
        {
            RedisConfig.DisableVerboseLogging = true;
            LogManager.LogFactory             = new ConsoleLogFactory(debugEnabled: true);

            var sentinel = new RedisSentinel(new [] {
                "127.0.0.1:26380",
                "127.0.0.1:26381",
                "127.0.0.1:26382",
            }, "mymaster");

            var redisManager = sentinel.Start();

            using (var client = redisManager.GetClient())
            {
                client.FlushAll();
            }

            using (var client = redisManager.GetClient())
            {
                client.IncrementValue("counter").ToString().Print();
            }

            "Force 'SENTINEL failover mymaster' then press enter...".Print();
            Console.ReadLine();

            try
            {
                using (var client = redisManager.GetClient())
                {
                    client.IncrementValue("counter").ToString().Print();
                }
            }
            catch (Exception ex)
            {
                ex.Message.Print();
            }

            try
            {
                using (var client = redisManager.GetClient())
                {
                    client.IncrementValue("counter").ToString().Print();
                }
            }
            catch (Exception ex)
            {
                ex.Message.Print();
            }

            try
            {
                using (var client = redisManager.GetClient())
                {
                    client.IncrementValue("counter").ToString().Print();
                }
            }
            catch (Exception ex)
            {
                ex.Message.Print();
            }

            Console.ReadLine();
        }
コード例 #33
0
        public void Execute()
        {
            RedisConfig.DisableVerboseLogging = true;
            RedisConfig.DefaultReceiveTimeout = 10000;

            using (var sentinel = new RedisSentinel(Config.SentinelHosts)) {
                // if (this._useRedisManagerPool) {
                //     sentinel.RedisManagerFactory = (masters, slaves) => new RedisManagerPool(masters);

                var redisManager = sentinel.Start();

                var i = 0;

                Timer clientTimer = null;

                void OnClientTimerOnElapsed(object state)
                {
                    Console.WriteLine();
                    Console.WriteLine("clientTimer.Elapsed: " + i++);

                    try {
                        string key = null;
                        using (var master = (RedisClient)redisManager.GetClient()) {
                            var counter = master.Increment("key", 1);
                            key = "key" + counter;
                            Console.WriteLine("Set key {0} in read/write client #{1}@{2}", key, master.Id, master.GetHostString());
                            master.SetValue(key, "value" + 1);
                        }

                        using (var readOnly = (RedisClient)redisManager.GetReadOnlyClient()) {
                            Console.WriteLine("Get key {0} in read-only client #{1}@{2}", key, readOnly.Id, readOnly.GetHostString());
                            var value = readOnly.GetValue(key);
                            Console.WriteLine("{0} = {1}", key, value);
                        }
                    } catch (ObjectDisposedException) {
                        Console.WriteLine("ObjectDisposedException detected, disposing timer...");
                        clientTimer?.Dispose();
                    } catch (Exception ex) {
                        Console.WriteLine("Error in Timer, {0}", ex);
                    }

                    if (i % 10 == 0)
                    {
                        Console.WriteLine(RedisStats.ToDictionary().ToJson());
                    }
                }

                clientTimer = new Timer(OnClientTimerOnElapsed, null, 0, 1000);

                Console.WriteLine("Sleeping for 5000ms...");
                Thread.Sleep(5000);

                Console.WriteLine("Failing over master...");
                sentinel.ForceMasterFailover();
                Console.WriteLine("master was failed over");

                Console.WriteLine("Sleeping for 20000ms...");
                Thread.Sleep(20000);

                try {
                    var debugConfig = sentinel.GetMaster();
                    using (var master = new RedisClient(debugConfig)) {
                        Console.WriteLine("Putting master '{0}' to sleep for 35 seconds...", master.GetHostString());
                        master.DebugSleep(35);
                    }
                } catch (Exception ex) {
                    Console.WriteLine("Error retrieving master for DebugSleep(), {0}", ex);
                }

                Console.WriteLine("After DEBUG SLEEP... Sleeping for 5000ms...");
                Thread.Sleep(5000);

                Console.WriteLine("RedisStats:");
                Console.WriteLine(RedisStats.ToDictionary().ToJson());
            }
        }
コード例 #34
0
        public void Does_scan_for_other_active_sentinels()
        {
            using (var sentinel = new RedisSentinel(SentinelHosts[0]) {
                ScanForOtherSentinels = true
            })
            {
                var clientsManager = sentinel.Start();

                Assert.That(sentinel.SentinelHosts, Is.EquivalentTo(SentinelHosts));

                using (var client = clientsManager.GetClient())
                {
                    Assert.That(client.GetHostString(), Is.EqualTo(MasterHosts[0]));
                }
            }
        }