public void RedisResolver_does_reset_when_detects_invalid_master() { var invalidMaster = new[] { SlaveHosts[0] }; var invalidSlaves = new[] { MasterHosts[0], SlaveHosts[1] }; using (var redisManager = new PooledRedisClientManager(invalidMaster, invalidSlaves)) { var resolver = (RedisResolver)redisManager.RedisResolver; using (var master = redisManager.GetClient()) { master.SetValue("KEY", "1"); Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); } using (var master = redisManager.GetClient()) { master.Increment("KEY", 1); Assert.That(master.GetHostString(), Is.EqualTo(MasterHosts[0])); } "Masters:".Print(); resolver.Masters.PrintDump(); "Slaves:".Print(); resolver.Slaves.PrintDump(); } }
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 Can_connect_to_ssl_azure_redis_with_PooledClientsManager() { using (var redisManager = new PooledRedisClientManager(connectionString)) using (var client1 = redisManager.GetClient()) using (var client2 = redisManager.GetClient()) { client1.Set("foo", "bar"); var foo = client2.GetValue("foo"); foo.Print(); } }
public void Can_Add_Update_and_Delete_Todo_item() { using (var redisManager = new PooledRedisClientManager()) using (var redis = redisManager.GetClient()) { var redisTodos = redis.As<Todo>(); var todo = new Todo { Id = redisTodos.GetNextSequence(), Content = "Learn Redis", Order = 1, }; redisTodos.Store(todo); Todo savedTodo = redisTodos.GetById(todo.Id); savedTodo.Done = true; redisTodos.Store(savedTodo); "Updated Todo:".Print(); redisTodos.GetAll().ToList().PrintDump(); redisTodos.DeleteById(savedTodo.Id); "No more Todos:".Print(); redisTodos.GetAll().ToList().PrintDump(); } }
public void Issue37_Cannot_add_unknown_client_back_to_pool_exception() { pool = new PooledRedisClientManager(); try { var threads = new Thread[100]; for (var i = 0; i < threads.Length; i++) { threads[i] = new Thread(Stuff); threads[i].Start(); } Debug.WriteLine("running, waiting 10secs.."); Thread.Sleep(10000); using (var redisClient = (RedisClient)pool.GetClient()) { Debug.WriteLine("shutdown Redis!"); redisClient.Shutdown(); } } catch (NotSupportedException nse) { Assert.Fail(nse.Message); } catch (Exception e) { Debug.WriteLine(e.Message); } Thread.Sleep(5000); }
public void Can_support_64_threads_using_the_client_simultaneously() { var before = Stopwatch.GetTimestamp(); const int noOfConcurrentClients = 64; //WaitHandle.WaitAll limit is <= 64 var clientAsyncResults = new List<IAsyncResult>(); using (var manager = new PooledRedisClientManager(TestConfig.MasterHosts, TestConfig.SlaveHosts)) { manager.GetClient().Run(x => x.FlushAll()); for (var i = 0; i < noOfConcurrentClients; i++) { var clientNo = i; var action = (Action)(() => UseClientAsync(manager, clientNo)); clientAsyncResults.Add(action.BeginInvoke(null, null)); } } WaitHandle.WaitAll(clientAsyncResults.ConvertAll(x => x.AsyncWaitHandle).ToArray()); Debug.WriteLine(string.Format("Completed in {0} ticks", (Stopwatch.GetTimestamp() - before))); RedisStats.ToDictionary().PrintDump(); }
/// <summary> /// 获取连接 /// </summary> /// <param name="sectionName">节点名称</param> public static IRedisClient GetClient(string sectionName = null) { if (pooledRedisClientManager == null) { redisSettings = sectionName == null?RedisSettings.GetConfig() : RedisSettings.GetConfig(sectionName); CreateManager(); } return(pooledRedisClientManager?.GetClient()); }
public void Can_recover_from_server_terminated_client_connection() { const int SleepHoldingClientMs = 5; const int SleepAfterReleasingClientMs = 0; const int loop = 1000; var admin = new RedisClient("localhost"); admin.SetConfig("timeout", "0"); var timeout = admin.GetConfig("timeout"); timeout.Print("timeout: {0}"); int remaining = loop; var stopwatch = Stopwatch.StartNew(); var clientManager = new PooledRedisClientManager(new[] { "localhost" }) { }; loop.Times(i => { ThreadPool.QueueUserWorkItem(x => { try { using (var client = (RedisClient)clientManager.GetClient()) { client.IncrementValue("key"); var val = client.Get<long>("key"); "#{0}, isConnected: {1}".Print(val, true); //client.IsSocketConnected() Thread.Sleep(SleepHoldingClientMs); } Thread.Sleep(SleepAfterReleasingClientMs); } catch (Exception ex) { ex.Message.Print(); } finally { remaining--; } }); }); while (remaining > 0) { Thread.Sleep(10); } "Elapsed time: {0}ms".Print(stopwatch.ElapsedMilliseconds); var managerStats = clientManager.GetStats(); managerStats.PrintDump(); }
/// <summary> /// 设置数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiry">过期时间</param> public void Set <T>(string key, T value, DateTime expiry) { if (value == null) { return; } if (expiry <= DateTime.Now) { Remove(key); return; } using var r = _pool?.GetClient(); if (r is null) { return; } r.SendTimeout = 1000; r.Set(key, value, expiry - DateTime.Now); }
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")); } }
public void Passwords_are_not_leaked_in_exception_messages() { const string password = "******"; try { var factory = new PooledRedisClientManager(password + "@" + TestConfig.SingleHost); // redis will throw when using password and it's not configured using (var redis = factory.GetClient()) { redis.SetEntry("Foo", "Bar"); } } catch (RedisResponseException ex) { Assert.That(ex.Message, Is.Not.StringContaining(password)); throw; } }
public void Can_recover_from_server_terminated_client_connection() { const int loop = 200; var admin = new RedisClient("localhost"); admin.SetConfig("timeout", "1"); var timeout = admin.GetConfig("timeout"); timeout.Print("timeout: {0}"); int remaining = loop; var clientManager = new PooledRedisClientManager(new[] { "localhost" }); loop.Times(i => { ThreadPool.QueueUserWorkItem(x => { try { using (var client = clientManager.GetClient()) { client.IncrementValue("key"); var val = client.Get<long>("key"); val.ToString().Print(); Thread.Sleep(2000); } } catch (Exception ex) { ex.Message.Print(); } finally { remaining--; } }); }); while (remaining > 0) { Thread.Sleep(100); } var managerStats = clientManager.GetStats(); managerStats.PrintDump(); }
public void Passwords_are_not_leaked_in_exception_messages() { const string password = "******"; Assert.Throws<ServiceStack.Redis.RedisResponseException>(() => { try { var factory = new PooledRedisClientManager(password + "@" + TestConfig.SingleHost); // redis will throw when using password and it's not configured using (var redis = factory.GetClient()) { redis.SetEntry("Foo", "Bar"); } } catch (RedisResponseException ex) { Assert.That(ex.Message, Is.Not.StringContaining(password)); throw; } }, "Expected an exception after Redis AUTH command; try using a password that doesn't match."); }
/// <summary> /// 获取 /// </summary> /// <returns></returns> public static RedisClient GetRedisClient() { return((RedisClient)RedisClientPool.GetClient()); }
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 SSL_can_support_64_threads_using_the_client_simultaneously() { var results = 100.Times(x => ModelWithFieldsOfDifferentTypes.Create(x)); var testData = TypeSerializer.SerializeToString(results); var before = Stopwatch.GetTimestamp(); const int noOfConcurrentClients = 64; //WaitHandle.WaitAll limit is <= 64 var clientAsyncResults = new List<IAsyncResult>(); using (var manager = new PooledRedisClientManager(TestConfig.MasterHosts, TestConfig.SlaveHosts)) { manager.GetClient().Run(x => x.FlushAll()); for (var i = 0; i < noOfConcurrentClients; i++) { var clientNo = i; var action = (Action)(() => UseClientAsync(manager, clientNo, testData)); clientAsyncResults.Add(action.BeginInvoke(null, null)); } } WaitHandle.WaitAll(clientAsyncResults.ConvertAll(x => x.AsyncWaitHandle).ToArray()); Debug.WriteLine(String.Format("Completed in {0} ticks", (Stopwatch.GetTimestamp() - before))); }
public void AddRedis() { using (BaseRepository <Room> _bR = new BaseRepository <Room>()) { using (var redisManager = new PooledRedisClientManager()) { using (var redis = redisManager.GetClient()) { var myId = SessionSetting.SessionSet <Domain.Domains.Hotel> .Get("LoginHotel").Id; HotelRoomDto modelList = _bR.Query <Hotel.Domain.Domains.Hotel>().Where(k => k.Id == myId).Select(k => new HotelRoomDto { hotelId = myId, Address = k.Address, AreaId = k.AreaId, Email = k.Email, Gym = k.Gym, HotelBar = k.HotelBar, HotelName = k.HotelName, Park = k.Park, Pool = k.Pool, Restaurant = k.Restaurant, RoomService = k.RoomService, Spa = k.Spa, TelNum = k.TelNum, Terrace = k.Terrace, WashingMachine = k.WashingMachine, roomDtos = k.rooms.Where(x => x.OtelId == k.Id).Select(x => new RoomDto { airConditioning = x.RoomType.airConditioning, Bathroom = x.RoomType.Bathroom, Fund = x.RoomType.Fund, Jakuzi = x.RoomType.Fund, Telephone = x.RoomType.Telephone, MiniBar = x.RoomType.MiniBar, TV = x.RoomType.TV, Wifi = x.RoomType.Wifi, OtelId = myId, RoomId = x.Id, Name = x.RoomType.Name, PersonCount = x.RoomType.PersonCount, Price = x.Price, Stock = x.Stock, roomImageDtos = x.roomImages.Where(a => a.RoomId == x.Id).Select(a => new RoomImageDto { IsActive = a.IsActive, Path = a.Path, Title = a.Title }).ToList() }).ToList() }).FirstOrDefault(); var data = redis.Get <HotelRoomDto>("otel_cache_" + myId); if (data != null) { redis.Set <HotelRoomDto>("otel_cache_" + myId, modelList); } else { redis.Add("otel_cache_" + myId, modelList); } } } } }
/// <summary> /// 客户端缓存操作对象 /// </summary> public static IRedisClient GetClient() { return(prcManager.GetClient()); }
protected IRedisClient GetClient() { return(m_clientManager.GetClient()); }
/// <summary> /// 设置单体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="t"></param> /// <param name="timeSpan"></param> /// <returns></returns> public static bool Add <T>(string key, T t) { try { using (IRedisClient redis = prcm.GetClient()) { return(redis.Set <T>(key, t, new TimeSpan(1, 0, 0))); } } catch (Exception ex) { LoggerHelper.Error(ex.ToString()); } return(false); }
static void Main2(string[] args) { var sbLogFactory = new StringBuilderLogFactory(); LogManager.LogFactory = sbLogFactory; var log = LogManager.GetLogger(typeof(Program)); var clientManager = new PooledRedisClientManager(new[] { "localhost" }) { PoolTimeout = 1000, }; var mqHost = new RedisMqServer(clientManager, retryCount: 2); var msgsProcessed = 0; var sum = 0; mqHost.RegisterHandler <Incr>(c => { var dto = c.GetBody(); sum += dto.Value; log.InfoFormat("Received {0}, sum: {1}", dto.Value, sum); msgsProcessed++; return(null); }); mqHost.Start(); 10.Times(i => { ThreadPool.QueueUserWorkItem(x => { using (var client = mqHost.CreateMessageQueueClient()) { try { log.InfoFormat("Publish: {0}...", i); client.Publish(new Incr { Value = i }); } catch (Exception ex) { log.InfoFormat("Start Publish exception: {0}", ex.Message); clientManager.GetClientPoolActiveStates().PrintDump(); clientManager.GetReadOnlyClientPoolActiveStates().PrintDump(); } Thread.Sleep(10); } }); }); ThreadPool.QueueUserWorkItem(_ => { using (var client = (RedisClient)clientManager.GetClient()) { client.SetConfig("timeout", "1"); var clientAddrs = client.GetClientList().ConvertAll(x => x["addr"]); log.InfoFormat("Killing clients: {0}...", clientAddrs.Dump()); try { clientAddrs.ForEach(client.ClientKill); } catch (Exception ex) { log.InfoFormat("Client exception: {0}", ex.Message); } } }); 20.Times(i => { using (var client = mqHost.CreateMessageQueueClient()) { try { log.InfoFormat("Publish: {0}...", i); client.Publish(new Incr { Value = i }); } catch (Exception ex) { log.InfoFormat("Publish exception: {0}", ex.Message); clientManager.GetClientPoolActiveStates().PrintDump(); clientManager.GetReadOnlyClientPoolActiveStates().PrintDump(); } } Thread.Sleep(1000); }); Thread.Sleep(2000); "Messages processed: {0}".Print(msgsProcessed); "Logs: ".Print(); sbLogFactory.GetLogs().Print(); Console.ReadKey(); }
public static void Init(IConfiguration configuration) { var redisConfigStr = configuration.GetSection("RedisConfig"); if (redisConfigStr == null) { throw new Exception("Redis 配置缺失"); } _redisConfig = new { WriteServerConStr = redisConfigStr["WriteServerConStr"], ReadServerConStr = redisConfigStr["ReadServerConStr"], RedisKey = redisConfigStr["RedisKey"] ?? "", MaxWritePoolSize = !redisConfigStr["MaxWritePoolSize"].IsNullOrEmpty() ? int.Parse(redisConfigStr["MaxWritePoolSize"]) : 5, MaxReadPoolSize = !redisConfigStr["MaxReadPoolSize"].IsNullOrEmpty() ? int.Parse(redisConfigStr["MaxReadPoolSize"]) : 5, AutoStart = redisConfigStr["AutoStart"].IsNullOrEmpty() || bool.Parse(redisConfigStr["AutoStart"]), DefaultDb = !redisConfigStr["DefaultDb"].IsNullOrEmpty() ? int.Parse(redisConfigStr["DefaultDb"]) : 0, ExpireTime = !redisConfigStr["ExpireTime"].IsNullOrEmpty() ? int.Parse(redisConfigStr["ExpireTime"]) : 1800, RecordeLog = redisConfigStr["RecordeLog"].IsNullOrEmpty() || bool.Parse(redisConfigStr["RecordeLog"]), }; var writeServerConStr = _redisConfig.WriteServerConStr.Split(','); var readServerConStr = _redisConfig.ReadServerConStr.Split(','); RedisConfig.VerifyMasterConnections = false; _pool = new PooledRedisClientManager(writeServerConStr, readServerConStr, new RedisClientManagerConfig { MaxWritePoolSize = _redisConfig.MaxWritePoolSize, MaxReadPoolSize = _redisConfig.MaxReadPoolSize, AutoStart = _redisConfig.AutoStart, DefaultDb = _redisConfig.DefaultDb, }); #region Sub //1.查看 // PUBSUB channels // 2.发布 // PUBLISH bxfq reload_table: all if (!((string)_redisConfig.RedisKey).IsNullOrEmpty()) { Task.Run(() => { var success = false; var subDoing = false; using (var redisClient = _pool.GetClient()) { using (var sub = redisClient.CreateSubscription()) { //接受到消息时 sub.OnMessage = (channel, msg) => { var m = $"时间:{DateTime.Now.ToStr()}, 从频道:{channel}上接受到消息:{msg}"; Console.WriteLine(); Log.Debug(m); var data = msg.Split(':'); if (data.Length == 2) { switch (data[0]) { case "reload_table": ServerConfig.ReloadConfig(data[1]); break; case "reload_param": break; default: Log.ErrorFormat("UnKnown CMD {0}", msg); break; } } else { Log.ErrorFormat("UnKnown data {0}", msg); } }; //订阅频道时 sub.OnSubscribe = (channel) => { var m = $"时间:{DateTime.Now.ToStr()}, 订阅:{channel}"; Console.WriteLine(m); Log.Debug(m); success = true; subDoing = false; }; //取消订阅频道时 sub.OnUnSubscribe = (channel) => { var m = $"时间:{DateTime.Now.ToStr()}, 取消订阅:{channel}"; Console.WriteLine(m); Log.Debug(m); success = false; subDoing = false; }; while (true) { if (subDoing || success) { continue; } subDoing = true; try { sub.SubscribeToChannels(_redisConfig.RedisKey); } catch (Exception e) { Log.Debug(e); success = false; subDoing = false; } Thread.Sleep(5 * 1000); } } } }); } #endregion Log.InfoFormat("Redis连接正常,Master:{0},Slave:{1}", _redisConfig.WriteServerConStr, _redisConfig.ReadServerConStr); }
public static void Set <T>(string key, T value, DateTime expiry) { if (CloseWrite) { return; } if (value == null) { return; } if (expiry <= DateTime.Now) { Remove(key); return; } //使用GetCacheClient() 来获取一个连接,他会在写的时候调用GetClient获取连接,读的时候调用GetReadOnlyClient获取连接,这样可以做到读写分离,从而利用redis的主从复制功能 using (var r = _pool.GetClient()) { try { r.Set(key, value, expiry - DateTime.Now); } catch (Exception ex) { Log.ErrorFormat("Redis连接出错:{0}", ex); } } }
static void Main(string[] args) { var redisUri = ConfigurationManager.AppSettings["Redis_Server_Uri"]; IRedisClientsManager clientManger = new PooledRedisClientManager(redisUri); PageRepository pageRepository = new PageRepository(clientManger.GetClient()); // bin\windows\zookeeper-server-start.bat config\zookeeper.properties // bin\windows\kafka-server-start.bat config\server.properties // bin\windows\kafka-console-consumer.bat --zookeeper localhost:2181 --topic PageLoadTime --from-beginning // kafka-console-producer.bat --broker-list localhost:9092 --topic PageLoadTime //// CONSUMER READING OFF THE QUEUE //var options = new KafkaOptions(new Uri("http://localhost:9092")); //var router = new BrokerRouter(options); //var redisClient = new RedisClient("127.0.0.1:6379"); //var db = redisClient.Instance(1); //var consumer = new Consumer(new ConsumerOptions("PageLoadTime", router)); //var allData = consumer.Consume(); //Task.Factory.StartNew(() => // { // int i = 0; // foreach (var data in allData) // { // if (string.IsNullOrEmpty(data.Key)) // { // continue; // } // Console.ForegroundColor = ConsoleColor.Green; // Console.WriteLine(string.Format("Reading {0} message => {1}", i, data.Value)); // Console.ForegroundColor = ConsoleColor.Yellow; // Console.WriteLine("----------------------------------------------------------"); // db.StringSetAsync(data.Key, data.Value.ToString(CultureInfo.InvariantCulture)); // i++; // } // }); var redisData = pageRepository.GetAll(); DisplayAll(redisData); // CONSUMER READING OFF THE QUEUE + REDIS var clientSettings = new MessageBusClient(); var router = clientSettings.GetClientRouter(); var consumer = new JsonConsumer <PageModel>(new ConsumerOptions("PageLoadTime", router)); var allData = consumer.Consume(); Task.Factory.StartNew(() => { foreach (var data in allData) { if (string.IsNullOrEmpty(data.Value.Key)) { continue; } var page = pageRepository.Store(data.Value); DisplaySingle(page); } }); Console.ReadKey(); }
/// <summary> /// 设置单体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="t"></param> /// <returns></returns> public static bool Item_Set <T>(string key, T t) { try { using (var redis = Prcm.GetClient()) { return(redis.Set <T>(key, t, new TimeSpan(1, 0, 0))); } } catch (Exception) { // ignored } return(false); }
public override IStorageConnection GetConnection() { return(new RedisConnection(_pooledManager.GetClient())); }
public void Can_MqServer_recover_from_server_terminated_client_connections() { LogManager.LogFactory = new ConsoleLogFactory(); var clientManager = new PooledRedisClientManager(new[] { "localhost" }) { }; var mqHost = new RedisMqServer(clientManager, retryCount: 2); var sum = 0; mqHost.RegisterHandler <Incr>(c => { var dto = c.GetBody(); sum += dto.Value; "Received {0}, sum: {1}".Print(dto.Value, sum); return(null); }); mqHost.Start(); 10.Times(i => { ThreadPool.QueueUserWorkItem(x => { using (var client = mqHost.CreateMessageQueueClient()) { "Publish: {0}...".Print(i); client.Publish(new Incr { Value = i }); Thread.Sleep(10); } }); }); ThreadPool.QueueUserWorkItem(_ => { using (var client = (RedisClient)clientManager.GetClient()) { client.SetConfig("timeout", "1"); var clientAddrs = client.GetClientList().ConvertAll(x => x["addr"]); "Killing clients: {0}...".Print(clientAddrs.Dump()); try { clientAddrs.ForEach(client.ClientKill); } catch (Exception ex) { "Client exception: {0}".Print(ex.Message); } } }); 20.Times(i => { using (var client = mqHost.CreateMessageQueueClient()) { "Publish: {0}...".Print(i); client.Publish(new Incr { Value = i }); } Thread.Sleep(2000); }); }
/// <summary> /// redis 16(0-15)个库切换 /// </summary> /// <param name="num"></param> /// <returns></returns> public static long Select(int num) { num = num > 15 ? 0 : num; using (IRedisClient redis = prcm.GetClient()) { return(redis.Db = num); } }
public void Start() { try { // Connect to the demo keyspace on our cluster running at 127.0.0.1 // Cluster cluster = Cluster.Builder().AddContactPoint("192.168.1.166").Build(); // ISession session = cluster.Connect("logistics"); //session.Execute("insert into dipper_frame (plate_number,time, acc, mileage,lat,lng) values ('测A12345', " + ConvertDateTimeInt(DateTime.Now) + ", true, 1234.123, 121.123456,31.654321)"); // RowSet rows = session.Execute("select * from dipper_frame"); InitDicGuid_Licenselate(); IRedisClientsManager clientManager = new PooledRedisClientManager(); IRedisClient client = clientManager.GetClient(); string[] lpArray = dicGuid_Licenselate.Values.Distinct().ToArray(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); try { using (var redisLocs = client.As <Loc>()) { //Loc l = redisLocs["苏BJ6615"]; //Console.WriteLine("车辆:" + l.lat); redisLocs.FlushAll(); foreach (string row in lpArray) { Console.WriteLine("车辆:" + row); //if (redisLocs.ContainsKey(row)) //{ // redisLocs.Sets[row].Clear(); // //if (l != null) // //{ // // //Console.WriteLine("车辆:" + l.lat); // // bool isRemove = redisLocs.RedisClient.Remove(row); // // Console.WriteLine("isRemove:" + isRemove); // //} //} Console.WriteLine("总车辆数:" + lpArray.Length); Console.WriteLine("车辆数:" + redisLocs.Lists[row].Count); //redisLocs.RemoveAllFromList(redisLocs.Lists[row]); Console.WriteLine("delete :" + row); } } } catch (Exception ex) { Console.WriteLine(ex); Console.Read(); //throw; } //Console.Read(); sw.Start(); using (var redisLocs = client.As <Loc>()) { foreach (string row in lpArray) { for (int i = 0; i < 1; i++)//一个月 { for (int j = 0; j < 2000; j++) { //string plateNumber = (string)row["plate_number"]; redisLocs.Lists[row].Add(new Loc { lat = 20 * j, lng = 20, plate_number = row, acc = true, mileage = 15 * j, time = DateTime.Now.AddMinutes(j) }); //Id = redisLocs.GetNextSequence(), //redisLocs.Store(new Loc { lat = (double)row["lat"], lng = (double)row["lng"], plate_number = (string)row["plate_number"], acc = (bool)row["acc"], mileage = (float)row["mileage"], time = ConvertFromDateTimeOffset((DateTimeOffset)row["time"]) });//); Console.WriteLine("insert :" + row); } } } } sw.Stop(); Console.WriteLine("insert complete:" + sw.Elapsed.Milliseconds); } catch (Exception ex) { Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace); } Console.Read(); }
/// <summary> /// 开启连接 /// </summary> public void Open() { _Redis = conn.GetClient(); _Redis.Db = DB; }
public override void Configure(Container container) { string sc = ConfigurationManager.AppSettings.Get("DbConnection"); string rchost = ConfigurationManager.AppSettings.Get("SessionRedisHost"); rchost = (string.IsNullOrEmpty(rchost))? "localhost:6379": rchost; string rcpassword = ConfigurationManager.AppSettings.Get("SessionRedisPassword"); string rcdbs = ConfigurationManager.AppSettings.Get("SessionRedisDb"); int rcdb; if (!int.TryParse(rcdbs, out rcdb)) { rcdb = 10; } string sstout = ConfigurationManager.AppSettings.Get("SessionTimeout"); int sessionTimeout; if (!int.TryParse(sstout, out sessionTimeout)) { sessionTimeout = 60 * 8; } var cacheClient = new BasicRedisClientManager(new string[] { rchost }, new string[] { rchost }, rcdb); cacheClient.GetClient().Password = rcpassword; container.Register <IAuthProvider>(new BdAuthProvider() { DbFactory = new ConnectionFactory(sc, FirebirdDialectProvider.Instance), AuthUserSession = new UserSession() { CacheClient = cacheClient, TimeOut = sessionTimeout, } }); string phost = ConfigurationManager.AppSettings.Get("CacheHost"); phost = (string.IsNullOrEmpty(phost))?"localhost:6379":phost; string pdbs = ConfigurationManager.AppSettings.Get("CacheDb"); int pdb; if (!int.TryParse(pdbs, out pdb)) { pdb = 9; } string ppassword = ConfigurationManager.AppSettings.Get("CachePassword"); var p = new PooledRedisClientManager(new string[] { phost }, new string[] { phost }, pdb); p.GetClient().Password = ppassword; container.Register <ICacheClient>(p); container.Register <IDbConnectionFactory>( new ConnectionFactory(sc, FirebirdDialectProvider.Instance) ); var config = new AppConfig(new ConfigurationResourceManager()); container.Register(config); if (!Directory.Exists(config.PhotoDirectory)) { Directory.CreateDirectory(config.PhotoDirectory); } //Mailer mailer = new Mailer(config); //container.Register(mailer); //HtmlReport.Register(this); //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method base.SetConfig(new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, { "Access-Control-Allow-Headers", "X-Requested-With" } }, }); log.InfoFormat("AppHost Configured: " + DateTime.Now); }
/// <summary> /// 获取单体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public static T Get <T>(string key) where T : class { using (IRedisClient redis = prcm.GetClient()) { redis.Password = Constant.RedisPwd; return(redis.Get <T>(key)); } }
internal static RedisClient GetClient() { return((RedisClient)_redis.GetClient()); }
//private static RedisClient redisCli = new RedisClient("192.168.101.165", 6379, "123456"); #region String /// <summary> /// 获取key,返回string格式 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetValueString(string key) { using (IRedisClient redis = PooleClient.GetClient()) { string value = redis.GetValue(key); return(value); } }
private static IRedisClient GetClient() { if (_prcm == null) throw new Exception("没有可用连接,请确认连接池是否已经加载."); return _prcm.GetClient(); }
public void Can_change_db_for_client() { using (var db1 = new PooledRedisClientManager(1, new string[] { TestConfig.SingleHost })) using (var db2 = new PooledRedisClientManager(2, new string[] { TestConfig.SingleHost })) { var val = Environment.TickCount; var key = "test" + val; var db1c = db1.GetClient(); var db2c = db2.GetClient(); try { db1c.Set(key, val); Assert.That(db2c.Get<int>(key), Is.EqualTo(0)); Assert.That(db1c.Get<int>(key), Is.EqualTo(val)); } finally { db1c.Remove(key); } } }
public static bool RunInLoop(PooledRedisClientManager clientManager, int iterations = 100, int sleepMs = 10, Action callback=null) { int count = 0; int errors = 0; 10.Times(i => { ThreadPool.QueueUserWorkItem(_ => { while (Interlocked.Decrement(ref iterations) >= 0) { using (var client = clientManager.GetClient()) { try { var result = client.Increment("test:failover", 1); Interlocked.Increment(ref count); if (count % (iterations / 10) == 0) lock (clientManager) Console.WriteLine("count: {0}, errors: {1}", count, errors); } catch (Exception ex) { Interlocked.Increment(ref errors); } Thread.Sleep(sleepMs); } } if (callback != null) { callback(); callback = null; } }); }); return true; }
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.")); } } }
public void Can_MqServer_recover_from_server_terminated_client_connections() { LogManager.LogFactory = new ConsoleLogFactory(); var clientManager = new PooledRedisClientManager(new[] { "localhost" }) { }; var mqHost = new RedisMqServer(clientManager, retryCount: 2); var sum = 0; mqHost.RegisterHandler<Incr>(c => { var dto = c.GetBody(); sum += dto.Value; "Received {0}, sum: {1}".Print(dto.Value, sum); return null; }); mqHost.Start(); 10.Times(i => { ThreadPool.QueueUserWorkItem(x => { using (var client = mqHost.CreateMessageQueueClient()) { "Publish: {0}...".Print(i); client.Publish(new Incr { Value = i }); Thread.Sleep(10); } }); }); ThreadPool.QueueUserWorkItem(_ => { using (var client = (RedisClient)clientManager.GetClient()) { client.SetConfig("timeout", "1"); var clientAddrs = client.GetClientList().ConvertAll(x => x["addr"]); "Killing clients: {0}...".Print(clientAddrs.Dump()); try { clientAddrs.ForEach(client.ClientKill); } catch (Exception ex) { "Client exception: {0}".Print(ex.Message); } } }); 20.Times(i => { using (var client = mqHost.CreateMessageQueueClient()) { "Publish: {0}...".Print(i); client.Publish(new Incr { Value = i }); } Thread.Sleep(2000); }); }
// ADD THIS PART TO YOUR CODE private async Task GetStartedDemo() { /* * this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);// ADD THIS PART TO YOUR CODE * await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "AngkasaPuraDB" }); * await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("AngkasaPuraDB"), new DocumentCollection { Id = "Flights" }); // ADD THIS PART TO YOUR CODE * await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("AngkasaPuraDB"), new DocumentCollection { Id = "Facilities" }); // ADD THIS PART TO YOUR CODE * await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("AngkasaPuraDB"), new DocumentCollection { Id = "News" }); * await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("AngkasaPuraDB"), new DocumentCollection { Id = "Luggages" }); * await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("AngkasaPuraDB"), new DocumentCollection { Id = "APTV" }); * await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("AngkasaPuraDB"), new DocumentCollection { Id = "Reports" }); */ //insert flights /* * try * { * using (var redisManager = new PooledRedisClientManager(3, ConStr)) * using (var redis = redisManager.GetClient()) * { * * var items = GetFlights(); * var redisTodos = redis.As<Flight>(); * foreach (var item in items) * { * item.Id = redisTodos.GetNextSequence(); * redisTodos.Store(item); * //await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Flights"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * } * catch (Exception de) * { * this.WriteToConsoleAndPromptToContinue("Error : {0}", de.Message); * } */ //dine using (var redisManager = new PooledRedisClientManager(3, ConStr)) using (var redis = redisManager.GetClient()) { var items = GetFacility(); var redisTodos = redis.As <Facility>(); foreach (var item in items) { item.Id = redisTodos.GetNextSequence(); redisTodos.Store(item); //await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Flights"), item); this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); } } /* * try * { * var items = GetFacility(); * foreach (var item in items) * { * await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Facilities"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * catch (DocumentClientException de) * { * this.WriteToConsoleAndPromptToContinue("Error : {0}", de.Message); * } */ /* * //news * using (var redisManager = new PooledRedisClientManager(3, ConStr)) * using (var redis = redisManager.GetClient()) * { * * var items = GetNews(); * var redisTodos = redis.As<News>(); * foreach (var item in items) * { * item.Id = redisTodos.GetNextSequence(); * redisTodos.Store(item); * //await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Flights"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * * try * { * var items = GetNews(); * foreach (var item in items) * { * await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "News"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * catch (DocumentClientException de) * { * this.WriteToConsoleAndPromptToContinue("Error : {0}", de.Message); * } * * //luggage * using (var redisManager = new PooledRedisClientManager(3, ConStr)) * using (var redis = redisManager.GetClient()) * { * * var items = GetLuggage(); * var redisTodos = redis.As<Luggage>(); * foreach (var item in items) * { * item.Id = redisTodos.GetNextSequence(); * redisTodos.Store(item); * //await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Flights"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * * try * { * var items = GetLuggage(); * foreach (var item in items) * { * await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Luggages"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * catch (DocumentClientException de) * { * this.WriteToConsoleAndPromptToContinue("Error : {0}", de.Message); * } * * //aptv * using (var redisManager = new PooledRedisClientManager(3, ConStr)) * using (var redis = redisManager.GetClient()) * { * * var items = GetAPTV(); * var redisTodos = redis.As<APTV>(); * foreach (var item in items) * { * item.Id = redisTodos.GetNextSequence(); * redisTodos.Store(item); * //await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Flights"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * * try * { * var items = GetAPTV(); * foreach (var item in items) * { * await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "APTV"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * catch (DocumentClientException de) * { * this.WriteToConsoleAndPromptToContinue("Error : {0}", de.Message); * } * * //report * using (var redisManager = new PooledRedisClientManager(3, ConStr)) * using (var redis = redisManager.GetClient()) * { * * var items = GetReport(); * var redisTodos = redis.As<Report>(); * foreach (var item in items) * { * item.Id = redisTodos.GetNextSequence(); * redisTodos.Store(item); * //await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Flights"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * * try * { * var items = GetReport(); * foreach (var item in items) * { * await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("AngkasaPuraDB", "Reports"), item); * this.WriteToConsoleAndPromptToContinue("Created item {0}", item.Id); * * } * } * catch (DocumentClientException de) * { * this.WriteToConsoleAndPromptToContinue("Error : {0}", de.Message); * }*/ }// ADD THIS PART TO YOUR CODE
public void Does_set_Client_on_Pooled_Connection() { using (var redisManager = new PooledRedisClientManager("localhost?Client=nunit")) using (var redis = redisManager.GetClient()) { var clientName = redis.GetClient(); Assert.That(clientName, Is.EqualTo("nunit")); } }
public IRedisClient GetClient() { return(m_redisManager.GetClient()); }
/// <summary> 客户端缓存操作对象 </summary> public IRedisClient GetClient() { return(prcm.GetClient()); }
/// <summary> /// 设置单体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="t"></param> /// <param name="timeSpan"></param> /// <returns></returns> public static bool Item_Set <T>(string key, T t) { try { using (IRedisClient redis = prcm.GetClient()) { return(redis.Set <T>(key, t, new TimeSpan(1, 0, 0))); } } catch (Exception ex) { } return(false); }
/// <summary> /// 检查Redis连接实例 /// </summary> /// <returns>是否连接畅通</returns> /// 时间:2016/11/9 23:15 /// 备注: public bool CheckedConnectInstance() { bool _result = true; try { using (IRedisClient redisClient = PRM.GetClient()) { redisClient.GetAllKeys(); } } catch (RedisException) { _result = false; } return(_result); }
public bool Can_connect_to_password_protected_redis_using_PooledRedisClientManager(string host) { try { var rPool = new PooledRedisClientManager(new List<string> { host }, new List<string> { host }); rPool.GetClient(); return true; } catch (Exception) { return false; } }
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(); } }
/// <summary> /// 设置单体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="t"></param> /// <param name="timeSpan"></param> /// <returns></returns> public static bool Set <T>(string key, T t) { using (IRedisClient redis = prcm.GetClient()) { return(redis.Set <T>(key, t)); } }
/// <summary> /// Get read and write connection /// </summary> /// <returns></returns> public static RedisClient GetClient() { return((RedisClient)_pooledRedis.GetClient()); }
private IRedisClient GetRedisClient() { return(clientManager.GetClient()); }