public void PooledRedisClientManager_alternates_hosts() { using (var redisManager = new PooledRedisClientManager(MasterHosts, SlaveHosts)) { using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.SetValue("KEY", "1"); } using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.Increment("KEY", 1); } 5.Times(i => { using (var readOnly = redisManager.GetReadOnlyClient()) { Assert.That(readOnly.GetHostString(), Is.EqualTo(SlaveHosts[i % SlaveHosts.Length])); Assert.That(readOnly.GetValue("KEY"), Is.EqualTo("2")); } }); using (var cahce = redisManager.GetCacheClient()) { Assert.That(cahce.Get<string>("KEY"), Is.EqualTo("2")); } } }
public void PooledRedisClientManager_alternates_hosts() { using var redisManager = new PooledRedisClientManager(MasterHosts, ReplicaHosts); using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.SetValue("KEY", "1"); } using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.Increment("KEY", 1); } 5.Times(i => { using var readOnly = redisManager.GetReadOnlyClient(); Assert.That(readOnly.GetHostString(), Is.EqualTo(ReplicaHosts[i % ReplicaHosts.Length])); Assert.That(readOnly.GetValue("KEY"), Is.EqualTo("2")); }); using (var cache = redisManager.GetCacheClient()) { Assert.That(cache.Get <string>("KEY"), Is.EqualTo("2")); } }
/// <summary> /// 鍙朙ist鐨勬墍鏈夊€? /// </summary> /// <param name="listid"></param> /// <param name="poolType"></param> /// <returns></returns> public static List <string> LGetAll(string listid, RedisPoolType poolType) { List <string> list = new List <string>(); PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { list = redis.GetAllItemsFromList(listid); if (redis != null) { redis.Dispose(); } } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(list); }
/// <summary> /// 鍙栨湁搴忛泦鍚堢殑骞堕泦 /// </summary> /// <param name="desKey"></param> /// <param name="zSetKeys"></param> /// <param name="aggregate"></param> /// <param name="poolType"></param> /// <returns></returns> public static long ZUnionStore(string desKey, string[] zSetKeys, RedisAggregate aggregate, RedisPoolType poolType) { long rtn = 0; PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { if (zSetKeys == null || zSetKeys.Length == 0) { redis.Remove(desKey); redis.AddItemToSortedSet(desKey, "-1", -1); rtn = 0; } else { string[] args = new string[] { "AGGREGATE", aggregate.ToString() }; rtn = redis.StoreUnionFromSortedSets(desKey, zSetKeys, args); } } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(rtn); }
/// <summary> /// 鍙栦竴涓湁搴忛泦鍚堥儴鍒嗘垚鍛? /// </summary> /// <param name="key"></param> /// <param name="fromScore"></param> /// <param name="toScore"></param> /// <param name="skip"></param> /// <param name="take"></param> /// <param name="isAsc">鏄惁鍗囧簭</param> /// <param name="poolType"></param> /// <returns></returns> public static List <string> ZGetRangeByScore(string key, long fromScore, long toScore, int?skip, int?take, bool isAsc, RedisPoolType poolType) { List <string> values = new List <string>(); PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { if (isAsc) { values = redis.GetRangeFromSortedSetByLowestScore(key, fromScore, toScore, skip, take); } else { values = redis.GetRangeFromSortedSetByHighestScore(key, fromScore, toScore, skip, take); } } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(values); }
public void Can_have_different_pool_size_and_host_configurations() { var writeHosts = new[] { "readwrite1" }; var readHosts = new[] { "read1", "read2" }; const int poolSizeMultiplier = 4; using (var manager = new PooledRedisClientManager(writeHosts, readHosts, new RedisClientManagerConfig { MaxWritePoolSize = writeHosts.Length * poolSizeMultiplier, MaxReadPoolSize = readHosts.Length * poolSizeMultiplier, AutoStart = true } ) ) { // A pool size of 4 will not block getting 4 clients using (var client1 = manager.GetClient()) { using (var client2 = manager.GetClient()) { using (var client3 = manager.GetClient()) { using (var client4 = manager.GetClient()) { AssertClientHasHost(client1, writeHosts[0]); AssertClientHasHost(client2, writeHosts[0]); AssertClientHasHost(client3, writeHosts[0]); AssertClientHasHost(client4, writeHosts[0]); } } } } // A pool size of 8 will not block getting 8 clients using (var client1 = manager.GetReadOnlyClient()) { using (var client2 = manager.GetReadOnlyClient()) { using (var client3 = manager.GetReadOnlyClient()) { using (var client4 = manager.GetReadOnlyClient()) { using (var client5 = manager.GetReadOnlyClient()) { using (var client6 = manager.GetReadOnlyClient()) { using (var client7 = manager.GetReadOnlyClient()) { using (var client8 = manager.GetReadOnlyClient()) { AssertClientHasHost(client1, readHosts[0]); AssertClientHasHost(client2, readHosts[1]); AssertClientHasHost(client3, readHosts[0]); AssertClientHasHost(client4, readHosts[1]); AssertClientHasHost(client5, readHosts[0]); AssertClientHasHost(client6, readHosts[1]); AssertClientHasHost(client7, readHosts[0]); AssertClientHasHost(client8, readHosts[1]); } } } } } } } } } }
public void PooledRedisClientManager_can_execute_CustomResolver() { var resolver = new FixedResolver(MasterHosts[0].ToRedisEndpoint(), ReplicaHosts[0].ToRedisEndpoint()); using var redisManager = new PooledRedisClientManager("127.0.0.1:8888") { RedisResolver = resolver }; using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.SetValue("KEY", "1"); } using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.Increment("KEY", 1); } Assert.That(resolver.NewClientsInitialized, Is.EqualTo(1)); 5.Times(i => { using (var replica = redisManager.GetReadOnlyClient()) { Assert.That(replica.GetHostString(), Is.EqualTo(ReplicaHosts[0])); Assert.That(replica.GetValue("KEY"), Is.EqualTo("2")); } }); Assert.That(resolver.NewClientsInitialized, Is.EqualTo(2)); redisManager.FailoverTo("127.0.0.1:9999", "127.0.0.1:9999"); 5.Times(i => { using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); Assert.That(master.GetValue("KEY"), Is.EqualTo("2")); } using (var replica = redisManager.GetReadOnlyClient()) { Assert.That(replica.GetHostString(), Is.EqualTo(ReplicaHosts[0])); Assert.That(replica.GetValue("KEY"), Is.EqualTo("2")); } }); Assert.That(resolver.NewClientsInitialized, Is.EqualTo(4)); }
/// <summary> /// 客户端缓存只读操作对象 /// </summary> /// <returns></returns> public static IRedisClient GetReadOnlyClient() { if (_prcm == null) { CreateManager(); } return(_prcm.GetReadOnlyClient()); }
/// <summary> /// 获取redis只读链接 /// </summary> /// <returns></returns> public static IRedisClient GetRedisReadOnlyClient() { if (redisPoolManager == null) { CreateRedisPool(); //如果连接池未被创建,则创建连接池 } return(redisPoolManager.GetReadOnlyClient()); //返回一个只读连接 }
private static IRedisClient GetReadOnlyClient() { if (prcm == null) { CreateManager(); } return(prcm.GetReadOnlyClient()); }
public bool CopyHashValue(string redis_hashname, string redis_hashkey, string couch_dbname) { using (var redis = _redis_pool.GetReadOnlyClient()) { var conveyor = GetCouchConveyor(couch_dbname); string value = redis.GetValueFromHash(redis_hashname, redis_hashkey); if (value != null) { conveyor.Convey(redis_hashkey, value); return(true); } else { return(false); } } }
/// <summary> /// 获取只读的Client /// </summary> public IRedisClient GetReadOnlyClient() { if (_redisClientManager == null) { CreateManager(); } return(_redisClientManager.GetReadOnlyClient()); }
private void button3_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { IRedisClient client1 = prcm.GetReadOnlyClient(); string value = client1.Get <string>("username2"); Debug.WriteLine(string.Format("{0}:{1} username2={2}", client1.Host, client1.Port, value)); client1.Dispose(); } }
public T Select <T>(string key) { if (RedisEnable) { return(SerializationHelper.DeserializeFromXml <T>(redisManager.GetReadOnlyClient().Get <string>(key))); } else { return(default(T)); } }
/** * @ 检查 key 是否存在于缓存中 * */ public override bool Contains(string key, string regionName = null) { bool succeed = false; using (IRedisClient client = redisPool.GetReadOnlyClient()) { succeed = client.ContainsKey(key); } return(succeed); }
public void Can_connect_to_Slaves_and_Masters_with_Password() { var factory = new PooledRedisClientManager(new[] { Config.MasterHost }, new[] { Config.SlaveHost }); using (var readWrite = factory.GetClient()) { using (var readOnly = factory.GetReadOnlyClient()) { readWrite.SetValue("Foo", "Bar"); var value = readOnly.GetValue("Foo"); Assert.That(value, Is.EqualTo("Bar")); } } }
public void Does_throw_TimeoutException_when_PoolTimeout_exceeded() { using (var manager = new PooledRedisClientManager(testReadWriteHosts, testReadOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 4, MaxReadPoolSize = 4, AutoStart = false, })) { manager.PoolTimeout = 100; manager.Start(); var masters = 4.Times(i => manager.GetClient()); try { manager.GetClient(); Assert.Fail("Should throw TimeoutException"); } catch (TimeoutException ex) { Assert.That(ex.Message, Does.StartWith("Redis Timeout expired.")); } var replicas = 4.Times(i => manager.GetReadOnlyClient()); try { manager.GetReadOnlyClient(); Assert.Fail("Should throw TimeoutException"); } catch (TimeoutException ex) { Assert.That(ex.Message, Does.StartWith("Redis Timeout expired.")); } } }
public IRedisClient GetReadOnlyClient(ref long initialDb, ref string[] readWriteHosts) //只读客户端 { CreateManager(ref (initialDb), ref (readWriteHosts)); try { return(_prcm.GetReadOnlyClient()); } catch (Exception ex) { MessageBox.Show("ERROR:" + ex.Message, "ERROR"); return(null); } }
public void Can_connect_to_Replicas_and_Masters_with_Password() { var factory = new PooledRedisClientManager( readWriteHosts: new[] { "[email protected]:6379" }, readOnlyHosts: new[] { "[email protected]:6380" }); using var readWrite = factory.GetClient(); using var readOnly = factory.GetReadOnlyClient(); readWrite.SetValue("Foo", "Bar"); var value = readOnly.GetValue("Foo"); Assert.That(value, Is.EqualTo("Bar")); }
protected override IRedisClient CreateClient(bool realOnly, string cmd) { IRedisClient client = null; if (realOnly) { client = _pool.GetReadOnlyClient(); } else { client = _pool.GetClient(); } return(client); }
/// <summary> /// 获取Redis客户端连接对象,有连接池管理。 /// </summary> /// <param name="isReadOnly">是否取只读连接。Get操作一般是读,Set操作一般是写</param> /// <returns></returns> public RedisClient GetRedisClient(bool isReadOnly = false) { if (pooledClientManager == null) { throw new ArgumentNullException(nameof(pooledClientManager)); } if (!isReadOnly) { return(pooledClientManager.GetClient() as RedisClient); } else { return(pooledClientManager.GetReadOnlyClient() as RedisClient); } }
public void Can_connect_to_Slaves_and_Masters_with_Password() { var factory = new PooledRedisClientManager( readWriteHosts: new[] { "[email protected]:6379" }, readOnlyHosts: new[] { "[email protected]:6380" }); using (var readWrite = factory.GetClient()) using (var readOnly = factory.GetReadOnlyClient()) { readWrite.SetEntry("Foo", "Bar"); var value = readOnly.GetEntry("Foo"); Assert.That(value, Is.EqualTo("Bar")); } }
/// <summary> /// 鏌ヨ涓€绯诲垪鐨勬湁搴忛泦鍚堟槸鍚﹀瓨鍦ㄤ竴瀹氳寖鍥寸殑鍊? /// </summary> /// <param name="zSetKeys"></param> /// <param name="keyPre"></param> /// <param name="keyExt"></param> /// <param name="fromScore"></param> /// <param name="toScore"></param> /// <param name="poolType"></param> /// <returns></returns> public static List <string> ZExists(List <string> zSetKeys, string keyPre, string keyExt, long fromScore, long toScore, RedisPoolType poolType) { List <string> existsKeys = new List <string>(); if (keyPre == null) { keyPre = ""; } if (keyExt == null) { keyExt = ""; } PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); var pipe = redis.CreatePipeline(); try { for (int i = 0; i < zSetKeys.Count; i++) { string key = zSetKeys[i]; pipe.QueueCommand(r => r.GetSortedSetCount(keyPre + key + keyExt, fromScore, toScore) , b => { if (b > 0) { existsKeys.Add(key); } }); } pipe.Flush(); } catch { throw; } finally { if (pipe != null) { pipe.Dispose(); } if (redis != null) { redis.Dispose(); } } return(existsKeys); }
/// <summary> /// 获取缓存 /// </summary> public static T GetCache <T>(string key, RedisEnum redisEnum = RedisEnum.Main) { try { using (IRedisClient iRedisClient = redisEnum == RedisEnum.Main ? MainRedisClientManager.GetReadOnlyClient() : CommonRedisClientManager.GetReadOnlyClient()) { iRedisClient.Password = redisEnum == RedisEnum.Main ? MainSlavePwd : CommonSlavePwd; return(iRedisClient.Get <T>(key)); } } catch (Exception ex) { FileHelper.logger.Warn("Redis获取缓存时异常 || " + ex.Message); } return(default(T)); }
public static string GetString(string key) { string result = ""; IRedisClient client = pool.GetReadOnlyClient(); try { result = client.Get <string>(key); } finally { client.Dispose(); } return(result); }
/// <summary> /// 获取Redis客户端连接对象,有连接池管理。 /// </summary> /// <param name="isReadOnly">是否取只读连接。Get操作一般是读,Set操作一般是写</param> /// <returns></returns> public RedisClient GetRedisClient(bool isReadOnly = false) { RedisClient result; if (!isReadOnly) { //RedisClientManager.GetCacheClient()会返回一个新实例,而且只提供一小部分方法,它的作用是帮你判断是否用写实例还是读实例 result = _pooledClientManager.GetClient() as RedisClient; } else { //如果你读写是两个做了主从复制的Redis服务端,那么要考虑主从复制是否有延迟。有一些读操作是否是即时的,需要在写实例中获取。 result = _pooledClientManager.GetReadOnlyClient() as RedisClient; } //如果你的需求需要经常切换Redis数据库,则下一句可以用。否则一般都只用默认0数据库,集群是没有数据库的概念。 //result.ChangeDb(Db); return(result); }
public override void InitCache(bool isReadAndWriter = true, string ip = "", int port = 0, string password = "") { if (redis == null) { ip = string.IsNullOrEmpty(ip) ? def_ip : ip; port = port == 0 ? def_port : port; password = string.IsNullOrEmpty(password) ? def_password : password; //单个redis服务 //redis = new RedisClient(ip, port, password); //集群服务 如果密码,格式如:pwd@ip:port var readAndWritePorts = new List <string> { "[email protected]:6379" }; var onlyReadPorts = new List <string> { "[email protected]:6378", "[email protected]:6377" }; var redisPool = new PooledRedisClientManager( readAndWritePorts, onlyReadPorts, new RedisClientManagerConfig { AutoStart = true, //最大读取链接 MaxReadPoolSize = 20, //最大写入链接 MaxWritePoolSize = 10 }) { //每个链接超时时间 ConnectTimeout = 20, //连接池超时时间 PoolTimeout = 60 }; lock (_lockCache) { redis = isReadAndWriter ? redisPool.GetClient() : redisPool.GetReadOnlyClient(); } } }
/// <summary> /// 澧為噺涓€涓狧ash鐨勫€? /// </summary> /// <param name="key"></param> /// <param name="subKey"></param> /// <param name="incrementBy"></param> /// <param name="poolType"></param> /// <returns></returns> public static bool HIncrease(string key, string subKey, int incrementBy, RedisPoolType poolType) { PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { redis.IncrementValueInHash(key, subKey, incrementBy); } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(true); }
/// <summary> /// 鎵归噺璁剧疆/澧炲姞涓€涓狧ash鐨勯敭鍊煎 /// </summary> /// <param name="key"></param> /// <param name="values"></param> /// <param name="poolType"></param> /// <returns></returns> public static bool HSetAll(string key, Dictionary <string, string> values, RedisPoolType poolType) { PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { redis.SetRangeInHash(key, values); } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(true); }
/// <summary> /// 璁剧疆涓€涓狧ash鍊? /// </summary> /// <param name="key"></param> /// <param name="subKey"></param> /// <param name="value"></param> /// <param name="poolType"></param> /// <returns></returns> public static bool HSet(string key, string subKey, string value, RedisPoolType poolType) { PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { redis.SetEntryInHash(key, subKey, value); } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(true); }
/// <summary> /// 鍙栦竴涓湁搴忛泦鍚堟墍鏈夋垚鍛? /// </summary> /// <param name="key"></param> /// <param name="poolType"></param> /// <returns></returns> public static List <string> ZGetAll(string key, RedisPoolType poolType) { List <string> values = new List <string>(); PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { values = redis.GetAllItemsFromSortedSet(key); } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(values); }
/// <summary> /// 鍙栦竴涓湁搴忛泦鍚堟墍鏈夋垚鍛樺強鍒嗘暟 /// </summary> /// <param name="key"></param> /// <param name="poolType"></param> /// <returns></returns> public static IDictionary <string, double> ZGetAllWithScores(string key, RedisPoolType poolType) { IDictionary <string, double> values = new Dictionary <string, double>(); PooledRedisClientManager pool = GetRedisPool(poolType); IRedisClient redis = pool.GetReadOnlyClient(); try { values = redis.GetAllWithScoresFromSortedSet(key); } catch { throw; } finally { if (redis != null) { redis.Dispose(); } } return(values); }
public void PooledRedisClientManager_can_execute_CustomResolver() { var resolver = new FixedResolver(MasterHosts[0].ToRedisEndpoint(), SlaveHosts[0].ToRedisEndpoint()); using (var redisManager = new PooledRedisClientManager("127.0.0.1:8888") { RedisResolver = resolver }) { using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.SetValue("KEY", "1"); } using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); master.Increment("KEY", 1); } Assert.That(resolver.NewClientsInitialized, Is.EqualTo(1)); 5.Times(i => { using (var slave = redisManager.GetReadOnlyClient()) { Assert.That(slave.GetHostString(), Is.EqualTo(SlaveHosts[0])); Assert.That(slave.GetValue("KEY"), Is.EqualTo("2")); } }); Assert.That(resolver.NewClientsInitialized, Is.EqualTo(2)); redisManager.FailoverTo("127.0.0.1:9999", "127.0.0.1:9999"); 5.Times(i => { using (var master = redisManager.GetClient()) { Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); Assert.That(master.GetValue("KEY"), Is.EqualTo("2")); } using (var slave = redisManager.GetReadOnlyClient()) { Assert.That(slave.GetHostString(), Is.EqualTo(SlaveHosts[0])); Assert.That(slave.GetValue("KEY"), Is.EqualTo("2")); } }); Assert.That(resolver.NewClientsInitialized, Is.EqualTo(4)); } }
public void Can_have_different_pool_size_and_host_configurations() { var writeHosts = new[] { "readwrite1" }; var readHosts = new[] { "read1", "read2" }; const int poolSizeMultiplier = 4; using (var manager = new PooledRedisClientManager(writeHosts, readHosts, new RedisClientManagerConfig { MaxWritePoolSize = writeHosts.Length * poolSizeMultiplier, MaxReadPoolSize = readHosts.Length * poolSizeMultiplier, AutoStart = true, } ) { RedisClientFactory = mockFactory.Object, } ) { //A poolsize of 4 will not block getting 4 clients using (var client1 = manager.GetClient()) using (var client2 = manager.GetClient()) using (var client3 = manager.GetClient()) using (var client4 = manager.GetClient()) { AssertClientHasHost(client1, writeHosts[0]); AssertClientHasHost(client2, writeHosts[0]); AssertClientHasHost(client3, writeHosts[0]); AssertClientHasHost(client4, writeHosts[0]); } //A poolsize of 8 will not block getting 8 clients using (var client1 = manager.GetReadOnlyClient()) using (var client2 = manager.GetReadOnlyClient()) using (var client3 = manager.GetReadOnlyClient()) using (var client4 = manager.GetReadOnlyClient()) using (var client5 = manager.GetReadOnlyClient()) using (var client6 = manager.GetReadOnlyClient()) using (var client7 = manager.GetReadOnlyClient()) using (var client8 = manager.GetReadOnlyClient()) { AssertClientHasHost(client1, readHosts[0]); AssertClientHasHost(client2, readHosts[1]); AssertClientHasHost(client3, readHosts[0]); AssertClientHasHost(client4, readHosts[1]); AssertClientHasHost(client5, readHosts[0]); AssertClientHasHost(client6, readHosts[1]); AssertClientHasHost(client7, readHosts[0]); AssertClientHasHost(client8, readHosts[1]); } mockFactory.VerifyAll(); } }
public void Does_throw_TimeoutException_when_PoolTimeout_exceeded() { using (var manager = new PooledRedisClientManager(testReadWriteHosts, testReadOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 4, MaxReadPoolSize = 4, AutoStart = false, })) { manager.PoolTimeout = 100; manager.Start(); var masters = 4.Times(i => manager.GetClient()); try { manager.GetClient(); Assert.Fail("Should throw TimeoutException"); } catch (TimeoutException ex) { Assert.That(ex.Message, Is.StringStarting("Redis Timeout expired.")); } var slaves = 4.Times(i => manager.GetReadOnlyClient()); try { manager.GetReadOnlyClient(); Assert.Fail("Should throw TimeoutException"); } catch (TimeoutException ex) { Assert.That(ex.Message, Is.StringStarting("Redis Timeout expired.")); } } }