public string BuildConnectionString(string host, int port) { var options = new ConfigurationOptions(); options.EndPoints.Add(host, port); return(options.ToString()); }
/// <summary> /// Creates the connection multiplexer. /// </summary> /// <returns>The connection multiplexer.</returns> private ConnectionMultiplexer CreateConnectionMultiplexer() { if (string.IsNullOrWhiteSpace(_options.Configuration)) { var configurationOptions = new ConfigurationOptions { ConnectTimeout = _options.ConnectionTimeout, Password = _options.Password, Ssl = _options.IsSsl, SslHost = _options.SslHost, AllowAdmin = _options.AllowAdmin, DefaultDatabase = _options.Database, AbortOnConnectFail = _options.AbortOnConnectFail, }; foreach (var endpoint in _options.Endpoints) { configurationOptions.EndPoints.Add(endpoint.Host, endpoint.Port); } return(ConnectionMultiplexer.Connect(configurationOptions.ToString())); } else { return(ConnectionMultiplexer.Connect(_options.Configuration)); } }
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()); }
public RedisConnection(ConfigurationOptions configOptions) { CheckConfigurationOptions(configOptions); _configOptions = configOptions; _connectionString = _configOptions.ToString(); }
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()); }
/// <summary> /// Creates the connection multiplexer. /// </summary> /// <returns>The connection multiplexer.</returns> private ConnectionMultiplexer CreateConnectionMultiplexer() { var dbconfig = _options.Value.DBConfig; if (string.IsNullOrWhiteSpace(dbconfig.ConnectionString)) { var configurationOptions = new ConfigurationOptions { ConnectTimeout = dbconfig.ConnectionTimeout, User = dbconfig.Username, Password = dbconfig.Password, Ssl = dbconfig.IsSsl, SslHost = dbconfig.SslHost, AllowAdmin = dbconfig.AllowAdmin, DefaultDatabase = dbconfig.Database, AbortOnConnectFail = dbconfig.AbortOnConnectFail, }; foreach (var endpoint in dbconfig.Endpoints) { configurationOptions.EndPoints.Add(endpoint.Host, endpoint.Port); } return(ConnectionMultiplexer.Connect(configurationOptions.ToString())); } else { _ = ConfigurationOptions.Parse(dbconfig.ConnectionString); return(ConnectionMultiplexer.Connect(dbconfig.ConnectionString)); } }
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); }
[InlineData(6380, true)] // all explicit // (note the 6379 port is closed) public void ConnectToAzure(int?port, bool ssl) { Skip.IfNoConfig(nameof(TestConfig.Config.AzureCacheServer), TestConfig.Current.AzureCacheServer); Skip.IfNoConfig(nameof(TestConfig.Config.AzureCachePassword), TestConfig.Current.AzureCachePassword); var options = new ConfigurationOptions(); options.CertificateValidation += ShowCertFailures(Writer); if (port == null) { options.EndPoints.Add(TestConfig.Current.AzureCacheServer); } else { options.EndPoints.Add(TestConfig.Current.AzureCacheServer, port.Value); } options.Ssl = ssl; options.Password = TestConfig.Current.AzureCachePassword; Log(options.ToString()); using (var connection = ConnectionMultiplexer.Connect(options)) { var ttl = connection.GetDatabase().Ping(); Log(ttl.ToString()); } }
public Fixture() { var options = new ConfigurationOptions { EndPoints = { "1.2.3.4" } }; ConnectionMultiplexer.Configuration.Returns(options.ToString()); }
/// <summary> /// 获取 <see cref="ConnectionMultiplexer" /> 实例。 /// </summary> /// <returns></returns> private static ConnectionMultiplexer GetConnectionMultiplexer() { var connStr = _options?.ToString() ?? _connStr; if (string.IsNullOrWhiteSpace(connStr)) { throw new ArgumentNullException(nameof(connStr)); } return(StackExchange.Redis.ConnectionMultiplexer.Connect(connStr)); }
public void redisconstr() { var option = new ConfigurationOptions() { Ssl = true, Proxy = Proxy.Twemproxy, AllowAdmin = true }; var str = option.ToString(); }
/// <summary> /// https://www.c-sharpcorner.com/article/creating-distributed-lock-with-redis-in-net-core/ /// https://github.com/catcherwong/Demos/blob/master/src/RedisLockDemo/RedisLockDemo/Program.cs /// </summary> private static ConnectionMultiplexer CreateConnection() { ConfigurationOptions configuration = new ConfigurationOptions { AbortOnConnectFail = false, ConnectTimeout = 5000, }; configuration.EndPoints.Add(REDIS_HOST, REDIS_PORT); return(ConnectionMultiplexer.Connect(configuration.ToString())); }
public RedisSettings(ConfigurationOptions configuration, int db = 0, bool master = false, System.IO.TextWriter connectionMultiplexerLog = null) { Db = db; Master = master; _configuration = configuration; Server = _configuration.ToString(); var split = Server.Split(':'); Host = split[0]; Port = split[1].AsInt(); _connectionMultiplexerLog = connectionMultiplexerLog; }
public void ResourceName_IncludesEndPoints() { var loopback = IPAddress.Loopback.ToString(); var broadcast = IPAddress.Broadcast.ToString(); var options = new ConfigurationOptions { EndPoints = { loopback, broadcast } }; _fixture.ConnectionMultiplexer.Configuration.Returns(options.ToString()); var target = _fixture.GetSut(); Assert.Contains(loopback, target.ResourceName); Assert.Contains(broadcast, target.ResourceName); }
public static string ConnectionStringUrlToRedisResource(string connectionStringUrl) { var(uri, _) = UrlUtility.UrlToResource(connectionStringUrl); var userInfo = uri.UserInfo.Split(':'); var configurationOptions = new ConfigurationOptions { EndPoints = { { uri.Host, uri.Port } }, ClientName = userInfo[0], Password = userInfo[1], AbortOnConnectFail = false }; return(configurationOptions.ToString()); }
public void Issue883_Exhaustive() { var old = CultureInfo.CurrentCulture; try { var all = CultureInfo.GetCultures(CultureTypes.AllCultures); Writer.WriteLine($"Checking {all.Length} cultures..."); foreach (var ci in all) { Writer.WriteLine("Testing: " + ci.Name); CultureInfo.CurrentCulture = ci; var a = ConfigurationOptions.Parse("myDNS:883,password=mypassword,connectRetry=3,connectTimeout=5000,syncTimeout=5000,defaultDatabase=0,ssl=true,abortConnect=false"); var b = new ConfigurationOptions { EndPoints = { { "myDNS", 883 } }, Password = "******", ConnectRetry = 3, ConnectTimeout = 5000, SyncTimeout = 5000, DefaultDatabase = 0, Ssl = true, AbortOnConnectFail = false, }; Writer.WriteLine($"computed: {b.ToString(true)}"); Writer.WriteLine("Checking endpoints..."); var c = a.EndPoints.Cast <DnsEndPoint>().Single(); var d = b.EndPoints.Cast <DnsEndPoint>().Single(); Check(nameof(c.Host), c.Host, d.Host); Check(nameof(c.Port), c.Port, d.Port); Check(nameof(c.AddressFamily), c.AddressFamily, d.AddressFamily); var fields = typeof(ConfigurationOptions).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Writer.WriteLine($"Comparing {fields.Length} fields..."); Array.Sort(fields, (x, y) => string.CompareOrdinal(x.Name, y.Name)); foreach (var field in fields) { Check(field.Name, field.GetValue(a), field.GetValue(b)); } } } finally { CultureInfo.CurrentCulture = old; } }
/// <summary> /// 创建Redis多连接复用器 /// </summary> /// <returns></returns> private ConnectionMultiplexer CreateConnectionMultiplexer() { var configurationOptions = new ConfigurationOptions() { ConnectTimeout = _options.ConnectionTimeout, Password = _options.Password, Ssl = _options.IsSsl, SslHost = _options.SslHost }; foreach (var endPoint in _options.EndPoints) { configurationOptions.EndPoints.Add(endPoint.Host, endPoint.Port); } return(ConnectionMultiplexer.Connect(configurationOptions.ToString())); }
private void RedisConnect() { try { if (this.innerContext != null) { this.innerContext.Close(); this.innerContext.Dispose(); this.innerContext = null; } } finally { log.Debug("Redis Reconnect: {0}", config.ToString(false)); this.innerContext = ConnectionMultiplexer.Connect(config); } }
public RedisCacheService(string host, int port, int cacheTime) { _cacheTime = cacheTime; _lazy = new Lazy <ConnectionMultiplexer>(() => { var conf = new ConfigurationOptions { AbortOnConnectFail = false, ConnectTimeout = 100, }; conf.EndPoints.Add(host, port); return(ConnectionMultiplexer.Connect(conf.ToString())); }); }
private void RedisConnect() { try { if (this.innerContext != null) { DeregisterConnectionEvents(this.innerContext); this.innerContext.Close(); this.innerContext.Dispose(); this.innerContext = null; } } finally { log.Debug("Redis Reconnect: {0}", config.ToString(false)); config.AbortOnConnectFail = false; this.innerContext = ConnectionMultiplexer.Connect(config); RegisterConnectionEvents(this.innerContext); } }
public void ConfigObject_Issue1407_ToStringIncludesSslProtocols() { var sslProtocols = SslProtocols.Tls12 | SslProtocols.Tls; var sourceOptions = new ConfigurationOptions { AbortOnConnectFail = false, Ssl = true, SslProtocols = sslProtocols, ConnectRetry = 3, ConnectTimeout = 5000, SyncTimeout = 5000, DefaultDatabase = 0, EndPoints = { { "endpoint.test", 6380 } }, Password = "******" }; var targetOptions = ConfigurationOptions.Parse(sourceOptions.ToString()); Assert.Equal(sourceOptions.SslProtocols, targetOptions.SslProtocols); }
public RedisConfiguration( string key, IList <ServerEndPoint> endpoints, int database = 0, string password = null, bool isSsl = false, string sslHost = null, int connectionTimeout = 5000, bool allowAdmin = false, bool keyspaceNotificationsEnabled = false, bool twemproxyEnabled = false, string strictCompatibilityModeVersion = null) { NotNullOrWhiteSpace(key, nameof(key)); NotNull(endpoints, nameof(endpoints)); if (endpoints.Count == 0) { throw new InvalidOperationException("List of endpoints must not be empty."); } Key = key; Database = database; Endpoints = endpoints; Password = password; IsSsl = isSsl; SslHost = sslHost; ConnectionTimeout = connectionTimeout; AllowAdmin = allowAdmin; KeyspaceNotificationsEnabled = keyspaceNotificationsEnabled; TwemproxyEnabled = twemproxyEnabled; StrictCompatibilityModeVersion = strictCompatibilityModeVersion; _configurationOptions = CreateConfigurationOptions(); // is used later on as key in the connection lookup, and this object should be consistent no matter which ctor is used ConnectionString = _configurationOptions.ToString(); }
/// <summary> /// 根据当前哨兵获取对应redis实例的连接字符串 /// </summary> /// <returns></returns> private string GetConnectionStringFromSentinel() { try { var activeSentinelServer = GetActiveServer(SentinelConnection, SentinelConnection.GetEndPoints()); var masterConnectionInfo = activeSentinelServer.SentinelGetMasterAddressByName(SentinelConfig.ServiceName); var slaveConnectionInfos = SanitizeHostsConfig(activeSentinelServer.SentinelSlaves(SentinelConfig.ServiceName)); var redisConfigs = new ConfigurationOptions { AllowAdmin = true, DefaultDatabase = SentinelConfig.DefaultDatabase, ConnectRetry = SentinelConfig.ConnectRetry, ConnectTimeout = SentinelConfig.ConnectTimeout, KeepAlive = SentinelConfig.KeepAlive, SyncTimeout = SentinelConfig.SyncTimeout, AbortOnConnectFail = false }; if (!string.IsNullOrEmpty(_password)) { redisConfigs.Password = _password; } redisConfigs.EndPoints.Add(masterConnectionInfo); foreach (var slaveInfo in slaveConnectionInfos) { redisConfigs.EndPoints.Add(slaveInfo); } return(redisConfigs.ToString()); } catch (Exception ex) { throw new Exception(string.Format("SESentinelClient.GetConnectionStringFromSentinel 连接到哨兵服务器({0})失败:{1}", SentinelConfig, ex.Message)); } }
/// <summary> /// /// </summary> /// <returns></returns> public ConnectionMultiplexer GetConnection() { ConnectionMultiplexer conn = null; lock (_aLivePool) { if (_aLivePool.Count > 0) { foreach (ConnectionMultiplexer cm in new IteratorIsolateCollection(_aLivePool.Keys)) { if (cm.IsConnected) { conn = cm; _aLivePool.Remove(cm); break; } else { Log.WriteWarning("RedisPools::GetConnection", "获取连接时发现cm.IsConnected==false,从连接池中移除"); cm.Close(); _aLivePool.Remove(cm); } } } } if (null == conn) { conn = getConnection(); if (!conn.IsConnected) { Log.WriteErrorLog("RedisPools::GetConnection", "获取连接时返回IsConnected为false. config = {0}", _config.ToString()); return(null); } } if (null != conn) { lock (_busyPool) { _busyPool[conn] = DateTime.Now; } } return(conn); }
static void Main(string[] args) { //最简单的配置只需要一个主机名就够了,会使用该主机的默认redis端口6379,额外的配置需要逗号分隔开,依次追加即可 ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost"); //端口号用通常的冒号表示,配置选项使用=将键值对分隔开 ConnectionMultiplexer redis2 = ConnectionMultiplexer.Connect("redis0:6380,redis1:6380,allowAdmin=true"); string connectionString = ""; //configurationOptions和connectionString 之间可以简单地转换 ConfigurationOptions configurationOptions = ConfigurationOptions.Parse(connectionString); connectionString = configurationOptions.ToString(); //常见用法是这样的:将基本的细节存储到字符串中,然后在运行时使用具体指定的配置细节 string connString = GetRedisConfiguration(); ConfigurationOptions options = ConfigurationOptions.Parse(connString); options.ClientName = GetAppName();//运行时才知道 options.AllowAdmin = true; var conn = ConnectionMultiplexer.Connect(options); //Microsoft Azure Redis 样例 var azureConn = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,ssl=true,password=..."); var config = new ConfigurationOptions { EndPoints = { { "redis0", 6379 }, { "redis1", 6380 } }, CommandMap = CommandMap.Create(new HashSet <string> { //排除一些命令 "INFO", "CONFIG", "CLUSTER", "PING", "ECHO", "CLIENT" }, available: false), KeepAlive = 180, DefaultVersion = new Version(2, 8, 8), Password = "******" }; //上面的config和下面的配置字符串是等价的 string configString = "redis0:6379,redis1:6380,keepAlive=180,version=2.8.8,$CLIENT=,$CLUSTER=,$CONFIG=,$ECHO=,$INFO=,$PING="; var commands = new Dictionary <string, string> { { "info", null }, //禁用info命令 { "select", "use" }, //use代替select命令 }; var option = new ConfigurationOptions { CommandMap = CommandMap.Create(commands), }; //option等价于$INFO=,$SELECT=use #region Twemproxy || Tiebreakers and Configuration Change Announcements //Twemproxy:https://github.com/twitter/twemproxy //Tiebreakers and Configuration Change Announcements var option2 = new ConfigurationOptions { Proxy = Proxy.Twemproxy, EndPoints = { "server" }, TieBreaker = "__Booksleeve_TieBreak", //默认值 ConfigurationChannel = "__Booksleeve_MasterChanged" //默认值 }; #endregion #region ReconnectRetryPolicy var option3 = new ConfigurationOptions { ConnectRetry = 6, ReconnectRetryPolicy = new ExponentialRetry(5000),// defaults maxDeltaBackoff to 10000 ms //retry# retry to re-connect after time in milliseconds //1 a random value between 5000 and 5500 //2 a random value between 5000 and 6050 //3 a random value between 5000 and 6655 //4 a random value between 5000 and 8053 //5 a random value between 5000 and 10000, since maxDeltaBackoff was 10000 ms //6 a random value between 5000 and 10000 //config.ReconnectRetryPolicy = new LinearRetry(5000); //retry# retry to re-connect after time in milliseconds //1 5000 //2 5000 //3 5000 //4 5000 //5 5000 //6 5000 }; #endregion }
public async Task ConnectToSSLServer(bool useSsl, bool specifyHost) { var server = TestConfig.Current.SslServer; int? port = TestConfig.Current.SslPort; string password = ""; bool isAzure = false; if (string.IsNullOrWhiteSpace(server) && useSsl) { // we can bounce it past azure instead? server = TestConfig.Current.AzureCacheServer; password = TestConfig.Current.AzureCachePassword; port = null; isAzure = true; } Skip.IfNoConfig(nameof(TestConfig.Config.SslServer), server); var config = new ConfigurationOptions { AllowAdmin = true, SyncTimeout = Debugger.IsAttached ? int.MaxValue : 5000, Password = password, }; var map = new Dictionary <string, string> { ["config"] = null // don't rely on config working }; if (!isAzure) { map["cluster"] = null; } config.CommandMap = CommandMap.Create(map); if (port != null) { config.EndPoints.Add(server, port.Value); } else { config.EndPoints.Add(server); } if (useSsl) { config.Ssl = useSsl; if (specifyHost) { config.SslHost = server; } config.CertificateValidation += (sender, cert, chain, errors) => { Log("errors: " + errors); Log("cert issued to: " + cert.Subject); return(true); // fingers in ears, pretend we don't know this is wrong }; } var configString = config.ToString(); Log("config: " + configString); var clone = ConfigurationOptions.Parse(configString); Assert.Equal(configString, clone.ToString()); using (var log = new StringWriter()) using (var muxer = ConnectionMultiplexer.Connect(config, log)) { Log("Connect log:"); lock (log) { Log(log.ToString()); } Log("===="); muxer.ConnectionFailed += OnConnectionFailed; muxer.InternalError += OnInternalError; var db = muxer.GetDatabase(); await db.PingAsync().ForAwait(); using (var file = File.Create("ssl-" + useSsl + "-" + specifyHost + ".zip")) { muxer.ExportConfiguration(file); } RedisKey key = "SE.Redis"; const int AsyncLoop = 2000; // perf; async await db.KeyDeleteAsync(key).ForAwait(); var watch = Stopwatch.StartNew(); for (int i = 0; i < AsyncLoop; i++) { try { await db.StringIncrementAsync(key, flags : CommandFlags.FireAndForget).ForAwait(); } catch (Exception ex) { Log($"Failure on i={i}: {ex.Message}"); throw; } } // need to do this inside the timer to measure the TTLB long value = (long)await db.StringGetAsync(key).ForAwait(); watch.Stop(); Assert.Equal(AsyncLoop, value); Log("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}", AsyncLoop, watch.ElapsedMilliseconds, (long)(AsyncLoop / watch.Elapsed.TotalSeconds), value); // perf: sync/multi-threaded // TestConcurrent(db, key, 30, 10); //TestConcurrent(db, key, 30, 20); //TestConcurrent(db, key, 30, 30); //TestConcurrent(db, key, 30, 40); //TestConcurrent(db, key, 30, 50); } }
public void ConnectToSSLServer(bool useSsl, bool specifyHost) { string host = null; const string path = @"D:\RedisSslHost.txt"; // because I choose not to advertise my server here! if (File.Exists(path)) host = File.ReadLines(path).First(); if (string.IsNullOrWhiteSpace(host)) Assert.Inconclusive("no ssl host specified at: " + path); var config = new ConfigurationOptions { CommandMap = CommandMap.Create( // looks like "config" is disabled new Dictionary<string, string> { { "config", null }, { "cluster", null } } ), EndPoints = { { host } }, AllowAdmin = true, SyncTimeout = Debugger.IsAttached ? int.MaxValue : 5000 }; if(useSsl) { config.Ssl = useSsl; if (specifyHost) { config.SslHost = host; } config.CertificateValidation += (sender, cert, chain, errors) => { Console.WriteLine("errors: " + errors); Console.WriteLine("cert issued to: " + cert.Subject); return true; // fingers in ears, pretend we don't know this is wrong }; } var configString = config.ToString(); Console.WriteLine("config: " + configString); var clone = ConfigurationOptions.Parse(configString); Assert.AreEqual(configString, clone.ToString(), "config string"); using(var log = new StringWriter()) using (var muxer = ConnectionMultiplexer.Connect(config, log)) { Console.WriteLine("Connect log:"); Console.WriteLine(log); Console.WriteLine("===="); muxer.ConnectionFailed += OnConnectionFailed; muxer.InternalError += OnInternalError; var db = muxer.GetDatabase(); db.Ping(); using (var file = File.Create("ssl-" + useSsl + "-" + specifyHost + ".zip")) { muxer.ExportConfiguration(file); } RedisKey key = "SE.Redis"; const int AsyncLoop = 2000; // perf; async db.KeyDelete(key, CommandFlags.FireAndForget); var watch = Stopwatch.StartNew(); for (int i = 0; i < AsyncLoop; i++) { db.StringIncrement(key, flags: CommandFlags.FireAndForget); } // need to do this inside the timer to measure the TTLB long value = (long)db.StringGet(key); watch.Stop(); Assert.AreEqual(AsyncLoop, value); Console.WriteLine("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}", AsyncLoop, (long)watch.ElapsedMilliseconds, (long)(AsyncLoop / watch.Elapsed.TotalSeconds), value); // perf: sync/multi-threaded TestConcurrent(db, key, 30, 10); //TestConcurrent(db, key, 30, 20); //TestConcurrent(db, key, 30, 30); //TestConcurrent(db, key, 30, 40); //TestConcurrent(db, key, 30, 50); } }
public void ConnectToSSLServer(bool useSsl, bool specifyHost) { string host = null; const string path = @"D:\RedisSslHost.txt"; // because I choose not to advertise my server here! if (File.Exists(path)) { host = File.ReadLines(path).First(); } if (string.IsNullOrWhiteSpace(host)) { Assert.Inconclusive("no ssl host specified at: " + path); } var config = new ConfigurationOptions { CommandMap = CommandMap.Create( // looks like "config" is disabled new Dictionary <string, string> { { "config", null }, { "cluster", null } } ), EndPoints = { { host } }, AllowAdmin = true, SyncTimeout = Debugger.IsAttached ? int.MaxValue : 5000 }; if (useSsl) { config.Ssl = useSsl; if (specifyHost) { config.SslHost = host; } config.CertificateValidation += (sender, cert, chain, errors) => { Console.WriteLine("errors: " + errors); Console.WriteLine("cert issued to: " + cert.Subject); return(true); // fingers in ears, pretend we don't know this is wrong }; } var configString = config.ToString(); Console.WriteLine("config: " + configString); var clone = ConfigurationOptions.Parse(configString); Assert.AreEqual(configString, clone.ToString(), "config string"); using (var log = new StringWriter()) using (var muxer = ConnectionMultiplexer.Connect(config, log)) { Console.WriteLine("Connect log:"); Console.WriteLine(log); Console.WriteLine("===="); muxer.ConnectionFailed += OnConnectionFailed; muxer.InternalError += OnInternalError; var db = muxer.GetDatabase(); db.Ping(); using (var file = File.Create("ssl-" + useSsl + "-" + specifyHost + ".zip")) { muxer.ExportConfiguration(file); } RedisKey key = "SE.Redis"; const int AsyncLoop = 2000; // perf; async db.KeyDelete(key, CommandFlags.FireAndForget); var watch = Stopwatch.StartNew(); for (int i = 0; i < AsyncLoop; i++) { db.StringIncrement(key, flags: CommandFlags.FireAndForget); } // need to do this inside the timer to measure the TTLB long value = (long)db.StringGet(key); watch.Stop(); Assert.AreEqual(AsyncLoop, value); Console.WriteLine("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}", AsyncLoop, (long)watch.ElapsedMilliseconds, (long)(AsyncLoop / watch.Elapsed.TotalSeconds), value); // perf: sync/multi-threaded TestConcurrent(db, key, 30, 10); //TestConcurrent(db, key, 30, 20); //TestConcurrent(db, key, 30, 30); //TestConcurrent(db, key, 30, 40); //TestConcurrent(db, key, 30, 50); } }
/// <summary> /// /// </summary> /// <returns></returns> public ConnectionMultiplexer GetConnection() { if (null == _conn) { _conn = getConnection(); } return(_conn); ConnectionMultiplexer conn = null; Random r = new Random(); lock (_aLivePool) { if (_aLivePool.Count > 0) { int index = r.Next(0, _aLivePool.Count); int eachIndex = 0; bool match = false; foreach (ConnectionMultiplexer cm in new IteratorIsolateCollection(_aLivePool.Keys)) { if (eachIndex == index || match) { match = true; if (cm.IsConnected) { conn = cm; //_aLivePool.Remove(cm); break; } else { Log.WriteWarning("RedisPools::GetConnection", "获取连接时发现cm.IsConnected==false,从连接池中移除"); cm.Close(); _aLivePool.Remove(cm); } } eachIndex++; } } } if (null == conn) { conn = getConnection(); if (!conn.IsConnected) { Log.WriteErrorLog("RedisPools::GetConnection", "获取连接时返回IsConnected为false. config = {0}", _config.ToString()); return(null); } } if (null != conn) { lock (_busyPool) { _busyPool[conn] = DateTime.Now; } } return(conn); }
/// <summary> /// 初始化Redis连接 /// </summary> /// <param name="config"></param> /// <param name="prefix"></param> /// <param name="logger"></param> /// <param name="dbIndex"></param> public static void Init(ConfigurationOptions config, string prefix, int dbIndex = 0, StackBaseLogger logger = null) { Init(config.ToString(), prefix, dbIndex, logger); }
public void ConnectToSSLServer(bool useSsl, bool specifyHost) { Skip.IfNoConfig(nameof(TestConfig.Config.SslServer), TestConfig.Current.SslServer); var config = new ConfigurationOptions { CommandMap = CommandMap.Create( // looks like "config" is disabled new Dictionary <string, string> { ["config"] = null, ["cluster"] = null } ), EndPoints = { { TestConfig.Current.SslServer, TestConfig.Current.SslPort } }, AllowAdmin = true, SyncTimeout = Debugger.IsAttached ? int.MaxValue : 5000 }; if (useSsl) { config.Ssl = useSsl; if (specifyHost) { config.SslHost = TestConfig.Current.SslServer; } config.CertificateValidation += (sender, cert, chain, errors) => { Output.WriteLine("errors: " + errors); Output.WriteLine("cert issued to: " + cert.Subject); return(true); // fingers in ears, pretend we don't know this is wrong }; } var configString = config.ToString(); Output.WriteLine("config: " + configString); var clone = ConfigurationOptions.Parse(configString); Assert.Equal(configString, clone.ToString()); using (var log = new StringWriter()) using (var muxer = ConnectionMultiplexer.Connect(config, log)) { Output.WriteLine("Connect log:"); Output.WriteLine(log.ToString()); Output.WriteLine("===="); muxer.ConnectionFailed += OnConnectionFailed; muxer.InternalError += OnInternalError; var db = muxer.GetDatabase(); db.Ping(); using (var file = File.Create("ssl-" + useSsl + "-" + specifyHost + ".zip")) { muxer.ExportConfiguration(file); } RedisKey key = "SE.Redis"; const int AsyncLoop = 2000; // perf; async db.KeyDelete(key, CommandFlags.FireAndForget); var watch = Stopwatch.StartNew(); for (int i = 0; i < AsyncLoop; i++) { db.StringIncrement(key, flags: CommandFlags.FireAndForget); } // need to do this inside the timer to measure the TTLB long value = (long)db.StringGet(key); watch.Stop(); Assert.Equal(AsyncLoop, value); Output.WriteLine("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}", AsyncLoop, (long)watch.ElapsedMilliseconds, (long)(AsyncLoop / watch.Elapsed.TotalSeconds), value); // perf: sync/multi-threaded TestConcurrent(db, key, 30, 10); //TestConcurrent(db, key, 30, 20); //TestConcurrent(db, key, 30, 30); //TestConcurrent(db, key, 30, 40); //TestConcurrent(db, key, 30, 50); } }