Exemple #1
0
 /// <summary>
 /// 设置缓存
 /// </summary>
 /// <typeparam name="T">缓存值类型</typeparam>
 /// <param name="key">缓存Key</param>
 /// <param name="t">缓存值</param>
 /// <param name="expiresTimeSpan">过期时间</param>
 public static void SetCache <T>(string key, T t, TimeSpan expiresTimeSpan)
 {
     using (var redisClient = redisManager.GetClient())
     {
         redisClient.Set <T>(key, t, expiresTimeSpan);
     }
 }
        public void Can_select_db()
        {
            var redisManager = new BasicRedisClientManager("127.0.0.1");

            using (var client = redisManager.GetClient())
            {
                client.Db = 2;
                client.Set("db", 2);
            }

            using (var client = redisManager.GetClient())
            {
                client.Db = 3;
                client.Set("db", 3);
            }

            using (var client = redisManager.GetClient())
            {
                client.Db = 2;
                var db = client.Get<int>("db");
                Assert.That(db, Is.EqualTo(2));
            }

            redisManager = new BasicRedisClientManager("127.0.0.1?db=3");
            using (var client = redisManager.GetClient())
            {
                var db = client.Get<int>("db");
                Assert.That(db, Is.EqualTo(3));
            }
        }
Exemple #3
0
        public void BasicRedisClientManager_alternates_hosts()
        {
            using (var redisManager = new BasicRedisClientManager(Config.MasterHosts, Config.SlaveHosts)) {
                using (var master = redisManager.GetClient()) {
                    Assert.That(master.GetHostString(), Is.EqualTo(Config.Sentinel6380));
                    master.SetValue("KEY", "1");
                }

                using (var master = redisManager.GetClient()) {
                    Assert.That(master.GetHostString(), Is.EqualTo(Config.Sentinel6380));
                    master.Increment("KEY", 1);
                }

                for (var i = 0; i < 5; i++)
                {
                    using (var readOnly = redisManager.GetReadOnlyClient()) {
                        Assert.That(readOnly.GetHostString(), Is.EqualTo(Config.Sentinel6381).Or.EqualTo(Config.Sentinel6382));
                        Assert.That(readOnly.GetValue("KEY"), Is.EqualTo("2"));
                    }
                }

                using (var cache = redisManager.GetCacheClient()) {
                    Assert.That(cache.Get <string>("KEY"), Is.EqualTo("2"));
                }
            }
        }
Exemple #4
0
        public void BasicRedisClientManager_alternates_hosts()
        {
            using (var redisManager = new BasicRedisClientManager(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"));
                }
            }
        }
Exemple #5
0
 /// <summary>
 /// 字符串设置
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <param name="ts"></param>
 /// <returns>设置是否成功</returns>
 public static bool stringSet(string key, string value, TimeSpan ts)
 {
     using (var redisClient = basicRedisClientManager.GetClient())
     {
         return(redisClient.Set <string>(key, value, ts));
     }
 }
 public void Push(string channel, string messsage)
 {
     using (var client = _clientManager.GetClient())
     {
         client.PushItemToList(channel, messsage);
     }
 }
        public void Can_select_db()
        {
            using (var redisManager = new BasicRedisClientManager(Config.MasterHost)) {
                using (var client = redisManager.GetClient()) {
                    client.Db = 2;
                    client.Set("db", 2);
                }

                using (var client = redisManager.GetClient()) {
                    client.Db = 3;
                    client.Set("db", 3);
                }

                using (var client = redisManager.GetClient()) {
                    client.Db = 2;
                    // ((RedisClient)client).ChangeDb(2);
                    var db = client.Get <int>("db");
                    Assert.That(db, Is.EqualTo(2));
                }
            }

            using (var redisManager = new BasicRedisClientManager(Config.MasterHost + "?db=3")) {
                using (var client = redisManager.GetClient()) {
                    var db = client.Get <int>("db");
                    Assert.That(db, Is.EqualTo(3));
                }
            }
        }
        public Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            var key = grainReference.ToKeyString();

            using (var client = _clients.GetClient())
            {
                var value = client.Remove(key);
            }

            return(Task.CompletedTask);
        }
Exemple #9
0
        public static void Main(string[] args)
        {
            // redis://clientid:password@localhost:6380?ssl=true&db=1
            var clientsManager = new BasicRedisClientManager("localhost:6379");

            try
            {
                _redisClient = clientsManager.GetClient();
                PrintCredentials();

                var valueMap = new Dictionary <string, string>();
                for (var i = 0; i < 100; i++)
                {
                    valueMap.Add($"key_{i}", $"value_{i}");
                }
                _redisClient.SetAll(valueMap);
                // _redisClient.RemoveAll(valueMap.Keys);

                Console.WriteLine("Getting all stored values");
                var values = _redisClient.GetAll <string>(valueMap.Keys);
                PrintDictionary(values);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public void Try_simulate_NRE_when_calling_GetAllEntriesFromHash_using_BasicRedisClientManager()
        {
            using (var redisManager = new BasicRedisClientManager(TestConfig.SingleHost))
                using (var redis = redisManager.GetClient())
                {
                    IRedisHash <string, Test> testHash = redis.As <Test>()
                                                         .GetHash <string>("test-hash");

                    Assert.That(testHash.Count, Is.EqualTo(0));

                    var contents = testHash.GetAll();
                    Assert.That(contents.Count, Is.EqualTo(0));

                    var test1 = new Test {
                        Id = 1, Name = "Name1"
                    };
                    var test2 = new Test {
                        Id = 2, Name = "Name2"
                    };
                    testHash["A"] = test1;
                    testHash["B"] = test2;

                    contents = testHash.GetAll();

                    Assert.That(contents, Is.EqualTo(new Dictionary <string, Test> {
                        ["A"] = test1,
                        ["B"] = test2,
                    }));

                    Assert.That(testHash["A"], Is.EqualTo(test1));
                    Assert.That(testHash["B"], Is.EqualTo(test2));
                }
        }
        public void Execute()
        {
            var basicRedisClientManager = new BasicRedisClientManager(Config.MasterHost);
            var queue = "FormSaved";

            Task.Run(() => {
                using (var client = basicRedisClientManager.GetReadOnlyClient()) {
                    Console.WriteLine($"Listening to {queue}");

                    var fromList = client.BlockingPopItemFromList(queue, TimeSpan.FromSeconds(60));

                    Console.WriteLine($"Received:{fromList}");
                }
            });
            Thread.Sleep(1000);

            Console.WriteLine("Enter something:");

            using (var client = basicRedisClientManager.GetClient()) {
                client.AddItemToList(queue, "something");
            }

            Console.WriteLine("Item added");

            Thread.Sleep(1000);
        }
Exemple #12
0
        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)
            );

            //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);
        }
Exemple #13
0
        public List <string> GetAllKeys()
        {
            var clientsManager = new BasicRedisClientManager(redisConnectionString);

            using (IRedisClient redis = clientsManager.GetClient())
            {
                redis.Db = database;
                return(redis.GetAllKeys());
            }
        }
Exemple #14
0
        public void SetRedisValue <T>(T value, string key)
        {
            var clientsManager = new BasicRedisClientManager(redisConnectionString);

            using (IRedisClient redis = clientsManager.GetClient())
            {
                redis.Db = database;
                redis.Set <T>(key, value);
            }
        }
Exemple #15
0
        public T GetRedisValue <T>(string key)
        {
            var clientsManager = new BasicRedisClientManager(redisConnectionString);

            using (IRedisClient redis = clientsManager.GetClient())
            {
                redis.Db = database;
                return(redis.Get <T>(key));
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            var clientManager = new BasicRedisClientManager("localhost:6379");

            using (var client = clientManager.GetClient())
            {
                client.FlushDb();
            }
            RedisCacheProvider.SetClientManager(clientManager);

            // ClientManager = new BasicRedisClientManager(ValidHost);
            //Redis = ClientManager.GetClient();
            //Redis.FlushDb();



            using (var session = NHibernateSessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var DepartmentObject = new Department {
                        Name = "IT", PhoneNumber = "962788700227"
                    };
                    session.Save(DepartmentObject);
                    transaction.Commit();
                    Console.WriteLine("Department Created: " + DepartmentObject.Name);
                    Console.ReadLine();

                    Department departmentAlias = null;
                    var        query           = session.QueryOver <Employee>()
                                                 .JoinAlias(x => x.EmployeeDepartment, () => departmentAlias, JoinType.LeftOuterJoin).Cacheable();
                    var c = query.List();

                    var d = query.List();

                    Console.WriteLine("Employee Listed: " + query.SingleOrDefault().FirstName);
                    Console.ReadLine();
                }
            }
            using (var session = NHibernateSessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    Department departmentAlias = null;
                    var        query           = session.QueryOver <Employee>()
                                                 .JoinAlias(x => x.EmployeeDepartment, () => departmentAlias, JoinType.LeftOuterJoin).Cacheable();
                    var c = query.List();

                    var d = query.List();

                    Console.WriteLine("Employee Listed: " + query.SingleOrDefault().FirstName);
                    Console.ReadLine();
                }
            }
        }
        private RedisClient CreateRedisClient(string metaDataConnStr, long metaDataDbIndex)
        {
            string[] hostPort = metaDataConnStr.Split(':');
            string   host     = hostPort[0];
            int      port     = int.Parse(hostPort[1]);

            // create and change to the meta data db
            BasicRedisClientManager clientManager = new BasicRedisClientManager((int)metaDataDbIndex, new string[] { metaDataConnStr });
            RedisClient             redisClient   = (RedisClient)clientManager.GetClient();

            return(redisClient);
        }
        public ScoreSetTest()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"appsettings.Test.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables();
            var conf         = builder.Build();
            var redisManager = new BasicRedisClientManager();

            _client = redisManager.GetClient();
            _client.FlushDb();
            _repo = new ScoreRepository(redisManager);
        }
Exemple #19
0
        public override IMessageService CreateMqServer(int retryCount = 1)
        {
            var redisManager = new BasicRedisClientManager();

            using (var redis = redisManager.GetClient())
            {
                redis.FlushAll();
            }
            return(new RedisMqServer(redisManager)
            {
                RetryCount = retryCount
            });
        }
        public Snapshot.Snapshot GetSnapshot(Guid aggregateId)
        {
            Snapshot.Snapshot snapshot = null;

            using (IRedisClient redis = clientsManager.GetClient())
            {
                var strSnapshot = redis.GetValue(aggregateId.ToString());

                if (strSnapshot != "")
                {
                    JsonSerializerSettings serializerSettings = new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.All
                    };

                    snapshot = JsonConvert.DeserializeObject <Snapshot.Snapshot>(
                        strSnapshot, serializerSettings);
                }
            }

            return(snapshot);
        }
Exemple #21
0
 /// <summary>
 /// Storage object with typeof(TEntity)
 /// </summary>
 /// <typeparam name="TEntity">TEntity</typeparam>
 /// <param name="entity">instance of TEntity</param>
 /// <param name="expired">expired time</param>
 public void Set <TEntity>(TEntity entity, DateTime datetime)
 {
     using (var client = clientManager.GetClient())
     {
         var storage = client.As <RedisStorageModel <TEntity> >();
         var model   = new RedisStorageModel <TEntity>(entity);
         model.Id = storage.GetNextSequence();
         storage.ExpireAt(model.Id, datetime);
         storage.Store(model);
     }
 }
Exemple #22
0
        private void redisPublish(string jsonTweet)
        {
            string lang = GetLanguage(jsonTweet);

            if (lang == null)
            {
                Console.WriteLine("\n" + jsonTweet);
                return;
            }
            jsonTweet = InjectAidrField(jsonTweet, lang);
            using (var redis = _redis.GetClient())
            {
                redis.PublishMessage(_redisChannel + "." + lang, jsonTweet);
            }
        }
Exemple #23
0
 public static IRedisClient GetDatabase()
 {
     if (manager == null)
     {
         lock (SyncLock) {
             try {
                 manager = new BasicRedisClientManager("localhost");
             }
             catch (Exception e) {
                 Console.WriteLine(e);
                 Console.WriteLine(e.InnerException);
                 return(null);
             }
         }
     }
     return(manager.GetClient());
 }
Exemple #24
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            var clientManager = new BasicRedisClientManager("localhost:6379");

            using (var client = clientManager.GetClient())
            {
                client.FlushDb();
            }

            RedisCacheProvider.SetClientManager(clientManager);

            var dbFile = HttpContext.Current.Server.MapPath("~/App_Data/sample.db");

            if (File.Exists(dbFile))
            {
                File.Delete(dbFile);
            }

            var configuration = Fluently.Configure()
                                .Database(
                SQLiteConfiguration.Standard.UsingFile(dbFile)
                )
                                .Mappings(m =>
            {
                m.FluentMappings.Add(typeof(BlogPostMapping));
            })
                                .ExposeConfiguration(cfg =>
            {
                cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true");
            })
                                .Cache(c =>
            {
                c.UseQueryCache().UseSecondLevelCache().ProviderClass <RedisCacheProvider>();
            })
                                .BuildConfiguration();

            new SchemaExport(configuration).Create(false, true);

            SessionFactory = configuration.BuildSessionFactory();
        }
 public void Can_change_db_for_client_BasicRedisClientManager()
 {
     using (var db1 = new BasicRedisClientManager(1, Config.MasterHost)) {
         using (var db2 = new BasicRedisClientManager(2, Config.MasterHost)) {
             var val       = Environment.TickCount;
             var key       = "test" + val;
             var db1Client = db1.GetClient();
             var db2Client = db2.GetClient();
             try {
                 db1Client.Set(key, val);
                 Assert.That(db2Client.Get <int>(key), Is.EqualTo(0));
                 Assert.That(db1Client.Get <int>(key), Is.EqualTo(val));
             } finally {
                 db1Client.Remove(key);
             }
         }
     }
 }
Exemple #26
0
        static void Main1(string[] args)
        {
            string rs = ConfigurationManager.AppSettings["RedisServerIP"].ToString();
            BasicRedisClientManager basicRedisClientManager = new BasicRedisClientManager(rs);

            using (var redisClient = basicRedisClientManager.GetClient())
            {
                redisClient.AddItemToSet("蜀国", "刘备");
                redisClient.AddItemToSet("蜀国", "关羽");
                redisClient.AddItemToSet("蜀国", "张飞");
                redisClient.GetAllKeys();
                IHasNamed <IRedisSet> rr            = redisClient.Sets;
                HashSet <string>      HashSetString = rr["蜀国"].GetAll();
                foreach (string str in HashSetString)
                {
                    Console.WriteLine(str);
                }
            }
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            var clientManager = new BasicRedisClientManager("localhost:6379");
            
            using (var client = clientManager.GetClient())
            {
                client.FlushDb();
            }

            RedisCacheProvider.SetClientManager(clientManager);

            var dbFile = HttpContext.Current.Server.MapPath("~/App_Data/sample.db");

            if (File.Exists(dbFile)) { File.Delete(dbFile); }

            var configuration = Fluently.Configure()
                .Database(
                    SQLiteConfiguration.Standard.UsingFile(dbFile)
                )
                .Mappings(m =>
                {
                    m.FluentMappings.Add(typeof(BlogPostMapping));
                })
                .ExposeConfiguration(cfg =>
                {
                    cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true");
                })
                .Cache(c =>
                {
                    c.UseQueryCache().UseSecondLevelCache().ProviderClass<RedisCacheProvider>();
                })
                .BuildConfiguration();

            new SchemaExport(configuration).Create(false, true);

            SessionFactory = configuration.BuildSessionFactory();
        }
 public void Can_change_db_for_client_BasicRedisClientManager()
 {
     using (var db1 = new BasicRedisClientManager(1, new string[] { TestConfig.SingleHost }))
         using (var db2 = new BasicRedisClientManager(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);
             }
         }
 }
Exemple #29
0
        public void Execute()
        {
//            RedisConfig.AssumeServerVersion = 4000;
//            RedisConfig.DisableVerboseLogging = false;
//            LogManager.LogFactory = new ConsoleLogFactory();

            var host = "localhost";
            var port = "6379";
            var db   = "9";

            var redisUri = $"{host}:{port}?db={db}";

            BasicRedisClientManager = new BasicRedisClientManager(redisUri);
            var queue = "FormSaved";

            while (true)
            {
                Task.Run(() => BlockingReceive(queue));
                Thread.Sleep(1000);

                Console.WriteLine("Restart Redis and press Enter...");
                Console.ReadLine();

                Console.WriteLine("Enter something:");
                var item = Console.ReadLine();

                if (!string.IsNullOrWhiteSpace(item))
                {
                    using (var client = BasicRedisClientManager.GetClient())
                    {
                        client.AddItemToList(queue, item);
                    }

                    Console.WriteLine("Item added");
                }

                Thread.Sleep(1000);
            }
        }
Exemple #30
0
 private void Command(Action <IRedisClient, string, CacheItem, TimeSpan> redisCommand, string key, CacheItem cacheItem, TimeSpan timeSpanExpiration)
 {
     if (Environment.MachineName.Equals(_host))
     {
         using (IRedisClientsManager redisManager = new BasicRedisClientManager(_writeHost))
         {
             using (IRedisClient client = redisManager.GetClient())
             {
                 redisCommand.Invoke(client, key, cacheItem, timeSpanExpiration);
             }
         }
     }
     else
     {
         using (PooledRedisClientManager redisManager = new PooledRedisClientManager(_writeHost))
         {
             using (IRedisClient client = redisManager.GetClient())
             {
                 redisCommand.Invoke(client, key, cacheItem, timeSpanExpiration);
             }
         }
     }
 }
Exemple #31
0
        public void RedisNativeClientTest1()
        {
            var connectionString = ConfigurationManager.AppSettings.Get("cache:redis");
            var key = "RedisParallelTest1";

            using (var redisManager = new BasicRedisClientManager(connectionString)) {
                redisManager.ConnectTimeout = 100;
                using (var client = (IRedisNativeClient)redisManager.GetClient()) {
                    client.Del(key);
                }
            }

            var actions = Enumerable.Repeat(1, 100).Select(i => new Action(() => {
                using (var redisManager = new BasicRedisClientManager(connectionString)) {
                    redisManager.ConnectTimeout = 100;
                    using (var client = (IRedisNativeClient)redisManager.GetClient()) {
                        client.Incr(key);
                    }
                }
            })).ToArray();

            Parallel.Invoke(actions);
        }
Exemple #32
0
        private object Retrieve(Func <IRedisClient, string, object> redisCommand, string key)
        {
            HostElement hostElement =
                _slaves.FirstOrDefault() ??
                new HostElement
            {
                Host     = _host,
                Port     = _port,
                Password = _password
            };
            string password = hostElement.Password;
            string host     = hostElement.Host;
            int    port     = hostElement.Port;

            var readOnlyHosts = !String.IsNullOrEmpty(password) ?
                                String.Format("{0}@{1}:{2}", password, host, port) :
                                String.Format("{0}:{1}", host, port);

            if (Environment.MachineName.Equals(host))
            {
                using (IRedisClientsManager redisManager = new BasicRedisClientManager(readOnlyHosts))
                {
                    using (IRedisClient client = redisManager.GetClient())
                    {
                        return(redisCommand.Invoke(client, key));
                    }
                }
            }

            using (var redisManager = new PooledRedisClientManager(readOnlyHosts))
            {
                using (IRedisClient client = redisManager.GetClient())
                {
                    return(redisCommand.Invoke(client, key));
                }
            }
        }
        public void BasicRedisClientManager_alternates_hosts()
        {
            using (var redisManager = new BasicRedisClientManager(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"));
                }
            }
        }
 private void Command(Action<IRedisClient, string, CacheItem, TimeSpan> redisCommand, string key, CacheItem cacheItem, TimeSpan timeSpanExpiration)
 {
     if (Environment.MachineName.Equals(_host))
     {
         using (IRedisClientsManager redisManager = new BasicRedisClientManager(_writeHost))
         {
             using (IRedisClient client = redisManager.GetClient())
             {
                 redisCommand.Invoke(client, key, cacheItem, timeSpanExpiration);
             }
         }
     }
     else
     {
         using (PooledRedisClientManager redisManager = new PooledRedisClientManager(_writeHost))
         {
             using (IRedisClient client = redisManager.GetClient())
             {
                 redisCommand.Invoke(client, key, cacheItem, timeSpanExpiration);
             }
         }
     }
 }
 public void Can_change_db_for_client_BasicRedisClientManager()
 {
     using (var db1 = new BasicRedisClientManager(1, new string[] { TestConfig.SingleHost }))
     using (var db2 = new BasicRedisClientManager(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);
         }
     }
 }
        private object Retrieve(Func<IRedisClient, string, object> redisCommand, string key)
        {
            HostElement hostElement =
                _slaves.FirstOrDefault() ??
                new HostElement
                    {
                        Host = _host,
                        Port = _port,
                        Password = _password
                    };
            string password = hostElement.Password;
            string host = hostElement.Host;
            int port = hostElement.Port;

            var readOnlyHosts = !String.IsNullOrEmpty(password) ?
                String.Format("{0}@{1}:{2}", password, host, port) :
                String.Format("{0}:{1}", host, port);

            if (Environment.MachineName.Equals(host))
            {
                using (IRedisClientsManager redisManager = new BasicRedisClientManager(readOnlyHosts))
                {
                    using (IRedisClient client = redisManager.GetClient())
                    {
                        return redisCommand.Invoke(client, key);
                    }
                }
            }

            using (var redisManager = new PooledRedisClientManager(readOnlyHosts))
            {
                using (IRedisClient client = redisManager.GetClient())
                {
                    return redisCommand.Invoke(client, key);
                }
            }
        }
Exemple #37
0
        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)
                );



            //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);
        }
Exemple #38
0
        public void RedisNativeClientTest1() {
            var connectionString = ConfigurationManager.AppSettings.Get("cache:redis");
            var key = "RedisParallelTest1";

            using (var redisManager = new BasicRedisClientManager(connectionString)) {
                redisManager.ConnectTimeout = 100;
                using (var client = (IRedisNativeClient)redisManager.GetClient()) {
                    client.Del(key);
                }
            }

            var actions = Enumerable.Repeat(1, 100).Select(i => new Action(() => {
                using (var redisManager = new BasicRedisClientManager(connectionString)) {
                    redisManager.ConnectTimeout = 100;
                    using (var client = (IRedisNativeClient)redisManager.GetClient()) {
                        client.Incr(key);
                    }
                }
            })).ToArray();

            Parallel.Invoke(actions);
        }