Exemplo n.º 1
0
        public static string GetRedisConnectionString()
        {
            var settings = ParseVCAP();

            if (null != settings.RedisPassword)
            {
                ConfigurationOptions config = new ConfigurationOptions
                {
                    EndPoints =
                    {
                        { settings.RedisHost }//, int.Parse(settings.RedisPort)}
                    },
                    CommandMap = CommandMap.Create(new HashSet <string>
                    { // EXCLUDE a few commands
                      /*"INFO", "CONFIG", "CLUSTER",*/
                        "PING", "ECHO",
                    }, available: false),
                    KeepAlive      = 180,
                    DefaultVersion = new Version(2, 8, 8),
                    Password       = settings.RedisPassword
                };
                return(config.ToString());
            }
            return(null);
        }
Exemplo n.º 2
0
        public string GetConnectionString()
        {
            var configurationOptions = new ConfigurationOptions
            {
                ConnectTimeout = _options.ConnectionTimeout,
                Password       = _options.Password,
                Ssl            = _options.IsSsl,
                SslHost        = _options.SslHost,
                CommandMap     = CommandMap.Create(_options.CommandMap)
            };

            try
            {
                configurationOptions.Password = configurationOptions.Password;
            }
            catch
            {
                _logger.LogCritical("Redis Password was not encrypted!!!");
            }

            var list = _options.Servers.Distinct();

            foreach (var endpoint in list)
            {
                configurationOptions.EndPoints.Add(endpoint.Host, int.Parse(endpoint.Port));
            }

            return(configurationOptions.ToString());
        }
Exemplo n.º 3
0
        public ConfigurationOptions GetOptions()
        {
            var config = new ConfigurationOptions
            {
                CommandMap           = CommandMap.Create(ExcludedCommands, false),
                KeepAlive            = KeepAlive,      // 60 sec to ensure connection is alive
                ConnectTimeout       = ConnectTimeout, // 5 sec
                SyncTimeout          = SyncTimeout,    // 5 sec
                AllowAdmin           = AllowAdmin,
                AbortOnConnectFail   = false,
                ReconnectRetryPolicy = new ExponentialRetry(500, 10000)
            };

            if (!string.IsNullOrEmpty(Password))
            {
                config.Password = Password;
            }

            foreach (var endpoint in Endpoints)
            {
                config.EndPoints.Add(endpoint.Host, endpoint.Port);
            }

            return(config);
        }
        private static ConnectionMultiplexer CreateConnection()
        {
            //在很多常见的情况下,StackExchange.Redis 将会自动的配置多个设置选项,包括服务器类型和版本,连接超时和主/从关系配置。可是有时候在Redis服务器这个命令是被禁止的。在这种情况下,提供更多的信息是非常有用的:
            ConfigurationOptions configOptions = new ConfigurationOptions
            {
                EndPoints =
                {
                    { "127.0.0.1", 6379 }
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                {
                    // 排除几个命令
                    //"INFO", "CONFIG", "CLUSTER", "PING", "ECHO", "CLIENT"
                }, available: false),
                AllowAdmin = true,
                Proxy      = Proxy.Twemproxy,
                Password   = "******",
            };

            var connect = ConnectionMultiplexer.Connect(configOptions);

            Console.WriteLine("create new redis connection success.");
            LogAsync("create new redis connection success.");
            RegisterConnectionEvent(connect);
            return(connect);
        }
Exemplo n.º 5
0
        private string GetConnectionString()
        {
            var redisConfig = new ConfigurationOptions
            {
                AbortOnConnectFail = false,
                Ssl                  = Convert.ToBoolean(this._redisConfig.SSL),
                ConnectRetry         = 3,
                ConnectTimeout       = 1000 * 30,
                AsyncTimeout         = 1000 * 3,
                SyncTimeout          = 1000 * 3,
                ReconnectRetryPolicy = new ExponentialRetry(5000, 30000),
                DefaultDatabase      = 0,
                AllowAdmin           = true,
                CommandMap           = CommandMap.Create(new HashSet <string> {
                    "INFO", "ECHO"
                }, available: false),
                EndPoints =
                {
                    { this._redisConfig.HostName, Convert.ToInt32(this._redisConfig.Port) }
                },
                Password = this._redisConfig.Key
            };

            return(redisConfig.ToString());
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            // Connection setup
            var configurationOptions = new ConfigurationOptions
            {
                EndPoints            = { "pub-redis-19354.eu-central-1-1.1.ec2.redislabs.com:19354" },
                KeepAlive            = 10,
                AbortOnConnectFail   = false,
                ConfigurationChannel = "",
                TieBreaker           = "",
                ConfigCheckSeconds   = 0,
                CommandMap           = CommandMap.Create(new HashSet <string>
                { // EXCLUDE a few commands
                    "SUBSCRIBE", "UNSUBSCRIBE", "CLUSTER"
                }, available: false),

                Password = "******"
            };

            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(configurationOptions);

            // Standard connection
            IDatabase db = redis.GetDatabase();

            RedisValue reply = db.HashGet("myHash", "myElem");

            Console.WriteLine(reply);
        }
Exemplo n.º 7
0
        public RedisCaching(IConfiguration config)
        {
            var redis = config.GetSection("Caching:Redis");
            ConfigurationOptions confRedis = new ConfigurationOptions
            {
                EndPoints =
                {
                    { redis["Host"], 6379 }
                },
                CommandMap = CommandMap.Create(new HashSet <string>()
                { // EXCLUDE a few commands
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false),
                KeepAlive            = 180,
                ConnectTimeout       = 2000,
                Password             = redis["Password"],
                ReconnectRetryPolicy = new ExponentialRetry(10000),
                ConnectRetry         = 2,
                AbortOnConnectFail   = false
            };

            //string connString = $"{redis["Host"]},password={redis["Password"]}";
            _multiplexer = ConnectionMultiplexer.Connect(confRedis);
            _client      = _multiplexer.GetDatabase();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="RedisAddressList"></param>
        /// <param name="Password">默认无密码</param>
        /// <param name="DbIndex"></param>
        public RedisExChangeHelper(IList <string> RedisAddressList = null, string Password = "", int DbIndex = -1)
        {
            ConfigurationOptions opt = new ConfigurationOptions
            {
                CommandMap = CommandMap.Create(new HashSet <string>
                {
                    "INFO",
                    "CONFIG",
                    "CLUSTER",
                    "PING",
                    "ECHO",
                    "CLIENT"
                }, available: false),
                KeepAlive = 120
            };

            if (RedisAddressList == null || RedisAddressList.Count == 0)
            {
                RedisAddressList.Add("127.0.0.1:6379");
            }

            if (!string.IsNullOrEmpty(Password))
            {
                opt.Password = Password;
            }


            foreach (var item in RedisAddressList)
            {
                opt.EndPoints.Add(item);
            }

            RedisMgr = ConnectionMultiplexer.Connect(opt);
            Redis    = RedisMgr.GetDatabase(DbIndex);
        }
Exemplo n.º 9
0
        public void RedisLabsSSL()
        {
            Skip.IfNoConfig(nameof(TestConfig.Config.RedisLabsSslServer), TestConfig.Current.RedisLabsSslServer);
            Skip.IfNoConfig(nameof(TestConfig.Config.RedisLabsPfxPath), TestConfig.Current.RedisLabsPfxPath);

            var cert = new X509Certificate2(TestConfig.Current.RedisLabsPfxPath, "");

            Assert.NotNull(cert);
            Writer.WriteLine("Thumbprint: " + cert.Thumbprint);

            int timeout = 5000;

            if (Debugger.IsAttached)
            {
                timeout *= 100;
            }
            var options = new ConfigurationOptions
            {
                EndPoints      = { { TestConfig.Current.RedisLabsSslServer, TestConfig.Current.RedisLabsSslPort } },
                ConnectTimeout = timeout,
                AllowAdmin     = true,
                CommandMap     = CommandMap.Create(new HashSet <string> {
                    "subscribe", "unsubscribe", "cluster"
                }, false)
            };

            options.TrustIssuer("redislabs_ca.pem");

            if (!Directory.Exists(Me()))
            {
                Directory.CreateDirectory(Me());
            }
#if LOGOUTPUT
            ConnectionMultiplexer.EchoPath = Me();
#endif
            options.Ssl = true;
            options.CertificateSelection += delegate
            {
                return(cert);
            };
            RedisKey key = Me();
            using (var conn = ConnectionMultiplexer.Connect(options))
            {
                var db = conn.GetDatabase();
                db.KeyDelete(key, CommandFlags.FireAndForget);
                string s = db.StringGet(key);
                Assert.Null(s);
                db.StringSet(key, "abc", flags: CommandFlags.FireAndForget);
                s = db.StringGet(key);
                Assert.Equal("abc", s);

                var latency = db.Ping();
                Log("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds);

                using (var file = File.Create("RedisLabs.zip"))
                {
                    conn.ExportConfiguration(file);
                }
            }
        }
Exemplo n.º 10
0
        private ConfigurationOptions GetConfigurationOptions(bool isForceAllowAdmin = false)
        {
            var endPointFirst = BedrockConfiguration.Cache.Redis.EndPoints.First();

            var returnValue = new ConfigurationOptions
            {
                AbortOnConnectFail   = BedrockConfiguration.Cache.Redis.AbortOnConnectFail,
                AllowAdmin           = isForceAllowAdmin ? true : BedrockConfiguration.Cache.Redis.AllowAdmin,
                ChannelPrefix        = BedrockConfiguration.Cache.Redis.ChannelPrefix,
                ClientName           = BedrockConfiguration.Cache.Redis.ClientName,
                CommandMap           = CommandMap.Create(new HashSet <string>(BedrockConfiguration.Cache.Redis.Commands), available: BedrockConfiguration.Cache.Redis.IsCommandsAvailable),
                ConfigCheckSeconds   = BedrockConfiguration.Cache.Redis.ConfigCheckSeconds,
                ConfigurationChannel = BedrockConfiguration.Cache.Redis.ConfigurationChannel,
                ConnectRetry         = BedrockConfiguration.Cache.Redis.ConnectRetry,
                ConnectTimeout       = BedrockConfiguration.Cache.Redis.ConnectTimeout,
                DefaultDatabase      = BedrockConfiguration.Cache.Redis.DefaultDatabase,
                DefaultVersion       = new Version(BedrockConfiguration.Cache.Redis.DefaultVersion),
                KeepAlive            = BedrockConfiguration.Cache.Redis.KeepAlive,
                Password             = BedrockConfiguration.Cache.Redis.Password,
                Proxy           = (Proxy)BedrockConfiguration.Cache.Redis.Proxy,
                ResolveDns      = BedrockConfiguration.Cache.Redis.ResolveDns,
                ResponseTimeout = BedrockConfiguration.Cache.Redis.ResponseTimeout,
                ServiceName     = BedrockConfiguration.Cache.Redis.ServiceName,
                Ssl             = BedrockConfiguration.Cache.Redis.Ssl,
                SslHost         = BedrockConfiguration.Cache.Redis.SslHost,
                SyncTimeout     = BedrockConfiguration.Cache.Redis.SyncTimeout,
                TieBreaker      = BedrockConfiguration.Cache.Redis.TieBreaker
            };

            SetEndPoints(returnValue);

            return(returnValue);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 获取可用连接,最小负载
        /// </summary>
        /// <returns></returns>
        private ConnectionMultiplexer GetLeastLoadedConn()
        {
            if (this.connectionPool.Count < this.poolSize)
            {
                lock (this.objLock)
                {
                    if (this.connectionPool.Count < this.poolSize)
                    {
                        var config = ConfigurationOptions.Parse(this.connectString, true);
                        config.AbortOnConnectFail = false;
                        config.KeepAlive          = 60;
                        config.SyncTimeout        = Math.Max(config.SyncTimeout, 10000);   //默认1秒,最小设置为10秒
                        config.SocketManager      = new SocketManager();                   //每个socketmanager维护了线程池,多建立几个提高并发
                        config.CommandMap         = CommandMap.Create(new HashSet <string> {
                            "SUBSCRIBE"
                        }, false);                                                                                                //禁用订阅发布,否则会多建立一条无用连接
                        var conn = ConnectionMultiplexer.Connect(config);
                        this.connectionPool.Add(conn);
                        return(conn);
                    }
                }
            }

            //最小负载
            var min = this.connectionPool.OrderBy(m => m.GetCounters().TotalOutstanding).First();

            return(min);
        }
Exemplo n.º 12
0
        public void RedisLabsSSL()
        {
            const string path    = @"d:\RedisLabsSslHost.txt";
            const string pfxPath = @"d:\RedisLabsUser.pfx";

            if (!File.Exists(path))
            {
                Assert.Inconclusive();
            }
            string hostAndPort = File.ReadAllText(path);
            int    timeout     = 5000;

            if (Debugger.IsAttached)
            {
                timeout *= 100;
            }
            var options = new ConfigurationOptions
            {
                EndPoints      = { hostAndPort },
                ConnectTimeout = timeout,
                AllowAdmin     = true,
                CommandMap     = CommandMap.Create(new HashSet <string> {
                    "subscribe", "unsubscribe", "cluster"
                }, false)
            };

            if (!Directory.Exists(Me()))
            {
                Directory.CreateDirectory(Me());
            }
#if LOGOUTPUT
            ConnectionMultiplexer.EchoPath = Me();
#endif
            options.Ssl = true;
            options.CertificateSelection += delegate {
                return(new X509Certificate2(pfxPath, ""));
            };
            RedisKey key = Me();
            using (var conn = ConnectionMultiplexer.Connect(options))
            {
                var db = conn.GetDatabase();
                db.KeyDelete(key);
                string s = db.StringGet(key);
                Assert.IsNull(s);
                db.StringSet(key, "abc");
                s = db.StringGet(key);
                Assert.AreEqual("abc", s);

                var latency = db.Ping();
                Console.WriteLine("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds);

                using (var file = File.Create("RedisLabs.zip"))
                {
                    conn.ExportConfiguration(file);
                }
            }
        }
Exemplo n.º 13
0
 public RedisRepository(string url)
 {
     _options            = ConfigurationOptions.Parse(url);
     _options.KeepAlive  = 120;
     _options.CommandMap = CommandMap.Create(new HashSet <string>
     {
         "INFO",
         "CONFIG",
         "PING",
         "ECHO",
         "CLIENT"
     }, false);
 }
Exemplo n.º 14
0
        static RedisRepository()
        {
            var configString = "Redis".ValueOfAppSetting();

            Options            = ConfigurationOptions.Parse(configString);
            Options.CommandMap = CommandMap.Create(new HashSet <string>
            {
                "INFO",
                "CONFIG",
                "PING",
                "ECHO",
                "CLIENT"
            }, false);
        }
Exemplo n.º 15
0
        static RedisWrapper()
        {
            var redisConfig = System.Configuration.ConfigurationManager.GetSection("redis") as RedisConfigurationSection;

            Options            = ConfigurationOptions.Parse(redisConfig.HostName);
            Options.CommandMap = CommandMap.Create(new HashSet <string>
            {
                "INFO",
                "CONFIG",
                "PING",
                "ECHO",
                "CLIENT"
            }, false);
        }
Exemplo n.º 16
0
        public LockBottleneckTest()
        {
            //Must set an environment variable for the "connection_string" we take care of this in docker compose.
            //Environment.SetEnvironmentVariable("connection_string", "redis:12000,connectRetry=3,connectTimeout=3000,abortConnect=false");
            ThreadPool.SetMinThreads(200, 200);
            ConfigurationOptions redisConfig = ConfigurationOptions.Parse(Environment.GetEnvironmentVariable("connection_string"), true);

            redisConfig.AbortOnConnectFail = false;
            redisConfig.AllowAdmin         = true;
            redisConfig.CommandMap         = CommandMap.Create(new HashSet <string>()
            {
                "KEYS", "DEL"
            }, available: false);
            connection = ConnectionMultiplexer.Connect(redisConfig);
        }
Exemplo n.º 17
0
        public ThrottleService(ConnectionMultiplexer redis, SiteConfig siteConfig, ILoggerFactory loggerFactory)
        {
            if (siteConfig.Stats != null && siteConfig.Stats.Enabled)
            {
                var options = ConfigurationOptions.Parse(siteConfig.Stats.Redis.Configuration);
                options.CommandMap = CommandMap.Create(siteConfig.Stats.Redis.CommandMap);

                options = RedisDnsHelper.CorrectOption(options);
                if (options != null)
                {
                    centralRedis = ConnectionMultiplexer.Connect(options);
                }
            }
            this.redis  = redis;
            this.logger = loggerFactory.CreateLogger <ThrottleService>();
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Redis !");

            ICacheOps cache = new RedisOps();


            var redisConfig             = "127.0.0.1";
            ConfigurationOptions config = new ConfigurationOptions
            {
                EndPoints =
                {
                    { "127.0.0.1", 6379 },
                    { "127.0.0.1", 6380 }
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                { // EXCLUDE a few commands
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false),
                KeepAlive      = 180,
                DefaultVersion = new Version(2, 8, 8),
                Password       = "******"
            };


            ConnectionMultiplexer redis = ConnectionMultiplexer.ConnectAsync(redisConfig).Result;

            IDatabase db = redis.GetDatabase();


            string value = "abcdefg";

            db.StringSet("mykey", value);
            string value2 = db.StringGet("mykey");

            Console.WriteLine(value2); // writes: "abcdefg"

            ISubscriber sub = redis.GetSubscriber();

            sub.Subscribe("messages", (channel, message) =>
            {
                Console.WriteLine((string)message);
            });

            sub.Publish("messages", "hello");
        }
Exemplo n.º 19
0
        /// <summary>
        /// AddRedisConfigInternal
        /// </summary>
        private static IServiceCollection AddRedisConfigInternal(this IServiceCollection serviceCollection)
        {
            var configurationOptions = new ConfigurationOptions
            {
                Password           = RedisConfiguration.Password,
                DefaultDatabase    = RedisConfiguration.DefaultDatabase,
                ConnectRetry       = RedisConfiguration.ConnectRetry,
                ConnectTimeout     = RedisConfiguration.ConnectTimeout,
                AllowAdmin         = RedisConfiguration.AllowAdmin,
                Ssl                = RedisConfiguration.Ssl,
                Proxy              = RedisConfiguration.Proxy,
                AbortOnConnectFail = RedisConfiguration.AbortOnConnectFail,
                SyncTimeout        = RedisConfiguration.SyncTimeout,
                AsyncTimeout       = RedisConfiguration.AsyncTimeout,
                ChannelPrefix      = RedisConfiguration.ChannelPrefix,
                ClientName         = RedisConfiguration.ClientName,
                DefaultVersion     = RedisConfiguration.DefaultVersion,
            };

            if (RedisConfiguration.CommandMap != null && RedisConfiguration.CommandMap.Count > 0)
            {
                configurationOptions.CommandMap = CommandMap.Create(RedisConfiguration.CommandMap);
            }
            configurationOptions.EndPoints.AddRange(RedisConfiguration.RedisServers.Select(s => ConvertHelper.ToEndPoint(s.Host, s.Port)).ToArray());

            serviceCollection.AddSingleton <IConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(configurationOptions));
            serviceCollection.AddSingleton(sp => sp.GetRequiredService <IConnectionMultiplexer>()
                                           .GetDatabase(RedisConfiguration.DefaultDatabase)
                                           );
            serviceCollection.AddSingleton(sp => sp.GetRequiredService <IConnectionMultiplexer>()
                                           .GetSubscriber()
                                           );
            serviceCollection.AddSingleton <ICacheClient, CacheClient>();
            serviceCollection.AddSingleton <IHashClient, HashClient>();
            serviceCollection.AddSingleton <IPubSubClient, PubSubClient>();
            serviceCollection.AddSingleton <IDataSerializer, JsonDataSerializer>();
            serviceCollection.AddSingleton <IDataCompressor, GZipDataCompressor>();
            serviceCollection.AddSingleton <CompressDataSerializer>();

            serviceCollection.AddLogging();

            DependencyResolver.SetDependencyResolver(serviceCollection);

            return(serviceCollection);
        }
Exemplo n.º 20
0
        private async Task <(int, IConnectionMultiplexer[])> Initialize()
        {
            var multiplexers = new IConnectionMultiplexer[_endPoints.Length];
            var keepAlive    = _lockOptions.KeepAlive ?? DefaultKeepAlive;
            var logWriter    = new LogWriter(_logger);

            var tasks = _endPoints.Select(
                async(endpoint, index) =>
            {
                var redisConfig = new ConfigurationOptions
                {
                    DefaultVersion     = new Version(4, 0),
                    AbortOnConnectFail = false,
                    EndPoints          = { endpoint },
                    CommandMap         = CommandMap.Create(new HashSet <string> {
                        "SUBSCRIBE"
                    }, available: false),
                    Password       = _lockOptions.Password,
                    ConnectTimeout = _lockOptions.ConnectionTimeout ?? DefaultConnectionTimeout,
                    SyncTimeout    = _lockOptions.SyncTimeout ?? DefaultSyncTimeout,
                    KeepAlive      = keepAlive,

                    // Time (seconds) to check configuration. This serves as a keep-alive for interactive sockets, if it is supported.
                    ConfigCheckSeconds = keepAlive
                };

                var multiplexer = await ConnectionMultiplexer.ConnectAsync(redisConfig, logWriter);
                multiplexer.ConnectionFailed   += OnConnectionFailed;
                multiplexer.ConnectionRestored += OnConnectionRestored;
                multiplexer.InternalError      += OnInternalError;
                multiplexer.ErrorMessage       += OnErrorMessage;

                multiplexers[index] = multiplexer;

                _logger.LogInformation(
                    "Tried to connect to RedLock endpoint at {host}:{port}. Connection status: {connectionStatus}",
                    endpoint.Host,
                    endpoint.Port,
                    multiplexer.IsConnected ? "active" : "disconnected");
            });

            await Task.WhenAll(tasks);

            return(keepAlive, multiplexers);
        }
Exemplo n.º 21
0
 private static Lazy <ConnectionMultiplexer> CreateMultiplexer()
 {
     return(new Lazy <ConnectionMultiplexer>(() =>
     {
         ConfigurationOptions redisConfig = ConfigurationOptions.Parse(ConnectionString, true);
         redisConfig.AbortOnConnectFail = false;
         redisConfig.AllowAdmin = false;
         redisConfig.CommandMap = CommandMap.Create(new HashSet <string>()
         {
             "KEYS", "DEL"
         }, available: false);
         ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(redisConfig);
         connection.ConnectionFailed += c_ConnectionFailed;
         connection.ConnectionRestored += c_ConnectionRestored;
         logger.LogDebug("Multiplexer is created.");
         return connection;
     }));
 }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            ConfigurationOptions config = new ConfigurationOptions
            {
                EndPoints =
                {
                    { "redis0", 6379 },
                    { "redis1", 6380 }
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                { // EXCLUDE a few commands
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false),
                KeepAlive      = 180,
                DefaultVersion = new Version(2, 8, 8),
                Password       = "******"
            };


            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(Config.Config.Host + ":" + Config.Config.port))
            {
                IServer   server   = redis.GetServer(Config.Config.Host, Config.Config.port);
                IDatabase database = redis.GetDatabase(0);
                database.StringSet("testkey", "testvalue");

                RedisValue value = database.StringGet("testkey");
                System.Console.WriteLine(value.ToString());


                const string Script   = "redis.call('set', @key, @value)";
                var          prepared = LuaScript.Prepare(Script);
                var          loaded   = prepared.Load(server);

                loaded.Evaluate(database, new { key = "key2", value = "value2" });
                value = database.StringGet("key2");
                System.Console.WriteLine(value.ToString());

                // var result = database.Execute("flushdb");
                // System.Console.WriteLine(result.ToString());
            }
        }
Exemplo n.º 23
0
        public RedisConnectionFactory(IOptions <RedisConfiguration> redis)
        {
            ConfigurationOptions config = new ConfigurationOptions();
            var ports = redis.Value.Port.Split(',');

            for (var i = 0; i < ports.Length; i++)
            {
                config.EndPoints.Add($"{redis.Value.Host}:{ports[i]}");
            }
            if (!redis.Value.IsDevelop)
            {
                config.Proxy      = Proxy.Twemproxy;
                config.CommandMap = CommandMap.Create(new HashSet <string>
                {
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false);
            }
            connection = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(config));
        }
Exemplo n.º 24
0
        IDatabase db;    //redissource

        public MessagesController()
        {
            ConfigurationOptions config = new ConfigurationOptions
            {
                EndPoints =
                {
                    { "redis-16883.c56.east-us.azure.cloud.redislabs.com", 16883 },
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                {     // EXCLUDE a few commands
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false),
                KeepAlive      = 180,
                DefaultVersion = new Version(5, 0, 4),
                Password       = "******"
            };

            redis = ConnectionMultiplexer.Connect(config);
            db    = redis.GetDatabase();
        }
Exemplo n.º 25
0
        /// <summary>
        /// Init configuration
        /// </summary>
        /// <returns></returns>
        private ConfigurationOptions InitConfigurationOptions()
        {
            ConfigurationOptions config = new ConfigurationOptions
            {
                CommandMap = CommandMap.Create(new HashSet <string>
                { // EXCLUDE a few commands
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false),
                AbortOnConnectFail   = _RedisKitOptions.AbortOnConnectFail,
                AllowAdmin           = _RedisKitOptions.AllowAdmin,
                ChannelPrefix        = _RedisKitOptions.ChannelPrefix,
                ConnectRetry         = _RedisKitOptions.ConnectRetry,
                ConnectTimeout       = _RedisKitOptions.ConnectTimeout,
                ConfigurationChannel = _RedisKitOptions.ConfigurationChannel,
                DefaultDatabase      = _RedisKitOptions.DefaultDatabase,
                KeepAlive            = _RedisKitOptions.KeepAlive,
                ClientName           = _RedisKitOptions.ClientName,
                Password             = _RedisKitOptions.Password,
                Proxy          = _RedisKitOptions.Proxy,
                ResolveDns     = _RedisKitOptions.ResolveDns,
                ServiceName    = _RedisKitOptions.ServiceName,
                Ssl            = _RedisKitOptions.Ssl,
                SslHost        = _RedisKitOptions.SslHost,
                SslProtocols   = _RedisKitOptions.SslProtocols,
                SyncTimeout    = _RedisKitOptions.SyncTimeout,
                TieBreaker     = _RedisKitOptions.TieBreaker,
                DefaultVersion = new Version(_RedisKitOptions.DefaultVersion),
                WriteBuffer    = _RedisKitOptions.WriteBuffer
            };

            //add endpoints
            var endPoints = SplitEndPoint(_RedisKitOptions.EndPoints, ",");

            foreach (var item in endPoints)
            {
                config.EndPoints.Add(item);
            }
            return(config);
        }
Exemplo n.º 26
0
        private static void Congfig()
        {
            var config = new ConfigurationOptions
            {
                EndPoints =
                {
                    { "redis0", 6379 }
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                {
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, false),
                KeepAlive      = 180,
                DefaultVersion = new Version(2, 8, 8),
                Password       = ""
            };

            using (var redis = ConnectionMultiplexer.Connect(config))
            {
            }
        }
Exemplo n.º 27
0
 public static IConnectionMultiplexer GetConnection()
 {
     if (MConnection != null && MConnection.IsConnected)
     {
         return(MConnection);
     }
     lock (_lock)
     {
         if (MConnection != null && MConnection.IsConnected)
         {
             return(MConnection);
         }
         MConnection?.Dispose();
         ConfigurationOptions config = new ConfigurationOptions
         {
             EndPoints =
             {
                 { "redis0", 6379 }
             },
             CommandMap = CommandMap.Create(new HashSet <string>
             {         // EXCLUDE a few commands
                 "INFO", "CONFIG", "CLUSTER",
                 "PING", "ECHO", "CLIENT"
             }, available: false),
             KeepAlive = 180,
             //DefaultVersion = new Version(2, 8, 8),
             Password = ""
         };
         try
         {
             MConnection = ConnectionMultiplexer.Connect(ConnectionStr);
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
     return(MConnection);
 }
Exemplo n.º 28
0
        private void Form1_Load(object sender, EventArgs e)
        {
            ConfigurationOptions config = new ConfigurationOptions
            {
                EndPoints =
                {
                    { "192.168.150.128", 6379 },
                    { "192.168.150.133", 6379 },
                    { "192.168.150.134", 6379 }
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                { // EXCLUDE a few commands
                    "CONFIG", "CLUSTER", "ECHO", "CLIENT"
                }, available: false),
                KeepAlive       = 60,
                DefaultDatabase = 0,
                ClientName      = "CSharp"
            };

            config.ReconnectRetryPolicy = new LinearRetry(5000);
            redis = ConnectionMultiplexer.Connect(config);
        }
Exemplo n.º 29
0
        public static IServiceCollection AddCaching(this IServiceCollection services)
        {
            ConfigurationOptions config = new ConfigurationOptions
            {
                EndPoints =
                {
                    { _appSettings.RedisHostName, _appSettings.RedisPort }
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                {     // EXCLUDE a few commands
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false),
                KeepAlive      = 180,
                DefaultVersion = new Version(2, 8, 8)
                                 //    Password = "******"
            };

            ConnectionMultiplexer cm = ConnectionMultiplexer.Connect(config);

            return(services.AddSingleton <IConnectionMultiplexer>(cm));
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            ConfigurationOptions config = new ConfigurationOptions
            {
                EndPoints =
                {
                    { "mexicotest.9s71yv.0001.use2.cache.amazonaws.com", 6379 }
                },
                CommandMap = CommandMap.Create(new HashSet <string>
                { // EXCLUDE a few commands
                    "INFO", "CONFIG", "CLUSTER",
                    "PING", "ECHO", "CLIENT"
                }, available: false),
                KeepAlive          = 180,
                DefaultVersion     = new Version(2, 8, 8),
                AbortOnConnectFail = false
            };
            var connectionMultiplexer = ConnectionMultiplexer.Connect(config);
            var database = connectionMultiplexer.GetDatabase();

            Console.WriteLine("Done!");
        }