protected CacheClientTestBase(ISerializer serializer)
		{
			Serializer = serializer;
		    var mux = ConnectionMultiplexer.Connect(new ConfigurationOptions
		    {
		        DefaultVersion = new Version(3, 0, 500),
		        EndPoints = {{"localhost", 6379}},
		        AllowAdmin = true
		    });

            Sut = new StackExchangeRedisCacheClient(mux, Serializer);
			Db = Sut.Database;
		}
コード例 #2
0
        public ICacheClient GetCurrent(string connectionString)
        {
            if (!HttpContext.Current.Items.Contains(REDIS_CONTEXT_KEY))
            {
                int port  = 6379;
                var parts = connectionString.Split(':');
                if (parts.Length == 2)
                {
                    Int32.TryParse(parts[1], out port);
                }

                ISerializer        serializer    = new NewtonsoftSerializer();
                RedisConfiguration configuration = new RedisConfiguration()
                {
                    Hosts = new RedisHost[]
                    {
                        new RedisHost()
                        {
                            Host = parts[0], Port = port
                        }
                    }
                };

                var redisClient = new StackExchangeRedisCacheClient(serializer, configuration);
                HttpContext.Current.Items.Add(REDIS_CONTEXT_KEY, redisClient);
            }

            return(HttpContext.Current.Items[REDIS_CONTEXT_KEY] as ICacheClient);
        }
コード例 #3
0
        public RedisCache()
        {
            var configuration = RedisCachingSectionHandlerExtension.GetConfig();

            if (configuration == null)
            {
                throw new ConfigurationErrorsException("Unable to locate <redisCacheClient> section into your configuration file. Take a look https://github.com/imperugo/StackExchange.Redis.Extensions");
            }
            var configurationOptions = new ConfigurationOptions
            {
                Ssl                = configuration.Ssl,
                AllowAdmin         = configuration.AllowAdmin,
                AbortOnConnectFail = configuration.AbortOnConnectFail,
                ConnectTimeout     = configuration.ConnectTimeout,
                Password           = configuration.Password
            };

            foreach (RedisHost redisHost in configuration.RedisHosts)
            {
                configurationOptions.EndPoints.Add(redisHost.Host, redisHost.CachePort);
            }

            var connectionMultiplexer = (IConnectionMultiplexer)ConnectionMultiplexer.Connect(configurationOptions);

            connectionMultiplexer.PreserveAsyncOrder = false;
            redis = new StackExchangeRedisCacheClient(connectionMultiplexer, new Serializer());
        }
コード例 #4
0
ファイル: RedisTests.cs プロジェクト: weedkiller/AABCMaster
        private static ICacheClient GetClient()
        {
            var redisConfiguration = new RedisConfiguration()
            {
                AbortOnConnectFail = true,
                //KeyPrefix = "_my_key_prefix_",
                Hosts = new RedisHost[]
                {
                    new RedisHost()
                    {
                        Host = "localhost"
                    },
                },
                AllowAdmin     = true,
                ConnectTimeout = 3000,
                Database       = 0,
                //Ssl = true,
                //Password = "******",
                ServerEnumerationStrategy = new ServerEnumerationStrategy()
                {
                    Mode       = ServerEnumerationStrategy.ModeOptions.All,
                    TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                    UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
                }
            };
            var serializer = new NewtonsoftSerializer();
            var client     = new StackExchangeRedisCacheClient(serializer, redisConfiguration);

            return(client);
        }
コード例 #5
0
        public RedisNoSqlDataSource()
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379");

            db          = redis.GetDatabase();
            cacheClient = new StackExchangeRedisCacheClient(serializer);
        }
コード例 #6
0
        public RedisRepository()
        {
            _redisUrl       = "127.0.0.1";
            RefreshingRedis = false;

            var redisConfiguration = new RedisConfiguration()
            {
                AbortOnConnectFail = true,
                KeyPrefix          = "",
                Hosts = new RedisHost[]
                {
                    new RedisHost()
                    {
                        Host = this._redisUrl, Port = 6379
                    }
                },
                AllowAdmin                = true,
                ConnectTimeout            = 3000,
                Database                  = 0,
                Ssl                       = false,
                Password                  = "",
                ServerEnumerationStrategy = new ServerEnumerationStrategy()
                {
                    Mode       = ServerEnumerationStrategy.ModeOptions.All,
                    TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                    UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
                }
            };

            _serializer        = new NewtonsoftSerializer();
            _cacheClient       = new StackExchangeRedisCacheClient(_serializer, redisConfiguration);
            _sqlLiteRepository = new SqlLiteRepository();
        }
コード例 #7
0
        public static GetDictionaryResult <T> GetAllPropperAsDictionary <T>(this StackExchangeRedisCacheClient cacheClient, IEnumerable <string> keys)
            where T : class
        {
            var keysList = keys.ToList();

            if (!keysList.Any())
            {
                return(new GetDictionaryResult <T>(null, keysList));
            }

            var redisKeyArray    = new RedisKey[keysList.Count];
            var redisResultArray = (RedisResult[])cacheClient.Database.ScriptEvaluate(CreateLuaScriptForMget(redisKeyArray, keysList), redisKeyArray);
            var result           = new GetDictionaryResult <T>();

            for (var index = 0; index < redisResultArray.Length; ++index)
            {
                if (!redisResultArray[index].IsNull)
                {
                    var obj = cacheClient.Serializer.Deserialize <T>((byte[])redisResultArray[index]);
                    result.Add(keysList[index], obj);
                }
                else
                {
                    result.AddMissing(keysList[index]);
                }
            }

            return(result);
        }
コード例 #8
0
        }                                                              // TODO use RedisCacheClient

        private RedisAccess()
        {
            _serializer = new NewtonsoftSerializer();
            var redisConfiguration = RedisCachingSectionHandler.GetConfig();

            RedisCacheClient = new StackExchangeRedisCacheClient(_serializer, redisConfiguration);
        }
コード例 #9
0
        public async Task <IEnumerable <string> > FindByKey(string keyPart)
        {
            var serializer  = new NewtonsoftSerializer();
            var cacheClient = new StackExchangeRedisCacheClient(_redis, serializer);

            return(await cacheClient.SearchKeysAsync($"*{keyPart}*"));
        }
        public NotificationRedisClientRequest(NotificationClientConfiguration configuration)
        {
            var serializer = new NewtonsoftSerializer();

            _cacheKey = configuration.RedisKey;
            _cache    = new StackExchangeRedisCacheClient(serializer, configuration.RedisConnectionString);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: wingertge/Miki
        async Task MainAsync()
        {
            Log.OnLog += (msg, level) => Console.WriteLine(msg);

            configuration.RegisterType(this);
            configuration.RegisterType(client);

            redisClient = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), RedisUrl);

            AddWebhookEvent(client, new DblVoteEvent(redisClient));

            if (File.Exists("./config.json"))
            {
                await configuration.ImportAsync(
                    new JsonSerializationProvider(),
                    "./config.json");
            }

            await configuration.ExportAsync(
                new JsonSerializationProvider(),
                "./config.json");

            client.Connect();

            Log.Message("running!");
        }
コード例 #12
0
        static RedisStackExchangeHelper()
        {
            if (lazyConnection == null || !lazyConnection.IsValueCreated)
            {
                lazyConnection = new Lazy <ConnectionMultiplexer>(() =>
                {
                    ConfigurationOptions config = new ConfigurationOptions()
                    {
                        SyncTimeout = 500000,
                        EndPoints   =
                        {
                            { host, port }
                        },
                        Password           = password,
                        AbortOnConnectFail = false,
                        AllowAdmin         = true
                    };
                    return(ConnectionMultiplexer.Connect(config));
                });
            }

            var serializer = new NewtonsoftSerializer();

            cacheClient = new StackExchangeRedisCacheClient(lazyConnection.Value, serializer);
        }
コード例 #13
0
        public async Task FlushDatabaseAsync()
        {
            var options = GetConfigurationOptions(true);

            using (var connection = GetConnection(options).Value)
                using (var client = new StackExchangeRedisCacheClient(connection, new NewtonsoftSerializer()))
                    await client.FlushDbAsync();
        }
コード例 #14
0
        public static bool Add <T>(this StackExchangeRedisCacheClient cacheClient, string key, T value, DateTimeOffset?expiresAt, TimeSpan?expiresIn,
                                   bool fireAndForget)
        {
            var numArray = cacheClient.Serializer.Serialize(value);

            expiresIn = expiresIn ?? expiresAt?.Subtract(DateTimeOffset.Now);
            return(cacheClient.Database.StringSet(key, numArray, expiresIn, When.Always, fireAndForget ? CommandFlags.FireAndForget : CommandFlags.None));
        }
コード例 #15
0
        public RedisConnection(NoSqlConnectionString connectionString)
        {
            _connection = ConnectionMultiplexer.Connect(connectionString.Url);

            var serializer = new NewtonsoftSerializer();

            _cacheClient = new StackExchangeRedisCacheClient(_connection, serializer);
        }
コード例 #16
0
        public void SaveAsync(CacheEnumeration.SaveType saveType)
        {
            var options = GetConfigurationOptions(true);

            using (var connection = GetConnection(options).Value)
                using (var client = new StackExchangeRedisCacheClient(connection, new NewtonsoftSerializer()))
                    client.SaveAsync((SaveType)saveType);
        }
コード例 #17
0
        private static void ReadProto(ConnectionMultiplexer redis)
        {
            var serializer  = new ProtobufSerializer();
            var cacheClient = new StackExchangeRedisCacheClient(serializer, "localhost");

            var person = cacheClient.Get <Person>("proto");

            Console.Write($"Person: [{person.Age}]");
        }
コード例 #18
0
        public void SaveTempProduct(Product product)
        {
            var serializer  = new NewtonsoftSerializer();
            var cacheClient = new StackExchangeRedisCacheClient(serializer);
            var productList = new List <Product>();

            productList.Add(product);
            cacheClient.Add("abc", product);
        }
コード例 #19
0
        public T Read <T>(string key)
        {
            serializer = new NewtonsoftSerializer();
            var redisConfiguration = RedisCachingSectionHandler.GetConfig();

            using (cacheClient = new StackExchangeRedisCacheClient(serializer, redisConfiguration))
            {
                return(cacheClient.Get <T>(key));
            }
        }
コード例 #20
0
        public static async Task <bool> AddAsync <T>(this StackExchangeRedisCacheClient cacheClient, string key, T value,
                                                     TimeSpan expiresIn, bool fireAndForget)
        {
            var numArray = await cacheClient.Serializer.SerializeAsync(value);

            var res = await cacheClient.Database.StringSetAsync(key, numArray, expiresIn, When.Always,
                                                                fireAndForget?CommandFlags.FireAndForget : CommandFlags.None);

            return(res);
        }
コード例 #21
0
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            var configuration = new ConfigurationOptions();

            configuration.EndPoints.Add("localhost:6379");
            configuration.ConnectTimeout = 200000;
            configuration.SyncTimeout    = 200000;
            RedisCacheClient             = new StackExchangeRedisCacheClient(ConnectionMultiplexer.Connect(configuration), serializer);
        }
コード例 #22
0
        public RedisCacheManager(string connectionString, TimeSpan?cacheTime = null, int errorRetryCount = 0,
                                 TimeSpan?errorRetryInterval = null)
        {
            _redis       = ConnectionMultiplexer.Connect(connectionString);
            _cacheClient = new StackExchangeRedisCacheClient(_redis, new MsgPackObjectSerializer());

            var retryStrategy = new FixedInterval(errorRetryCount, errorRetryInterval ?? TimeSpan.Zero);

            _retryPolicy = new RetryPolicy <RedisCacheTransientErrorDetectionStrategy>(retryStrategy);
            _cacheTime   = cacheTime ?? TimeSpan.FromDays(7);
        }
コード例 #23
0
 public RedisInterprocessMessageReceiver(IAppRedisConfiguration configuration,
                                         IInterprocessIdentity interprocessIdentity,
                                         IMessageDeliverer messageDeliverer, ILogger logger)
 {
     _configuration        = configuration;
     _interprocessIdentity = interprocessIdentity;
     _messageDeliverer     = messageDeliverer;
     _logger   = logger;
     _client   = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), _configuration.ToRedisConfiguration());
     _handlers = new Dictionary <Type, MessageReceivedHandler>();
 }
コード例 #24
0
        public static async Task <bool> AddAsync <T>(this StackExchangeRedisCacheClient cacheClient, string key, T value, DateTimeOffset?expiresAt,
                                                     TimeSpan?expiresIn, bool fireAndForget) where T : class
        {
            var numArray = await cacheClient.Serializer.SerializeAsync(value);

            expiresIn = expiresIn ?? expiresAt?.Subtract(DateTimeOffset.Now);
            var res = await cacheClient.Database.StringSetAsync(key, numArray, expiresIn, When.Always,
                                                                fireAndForget?CommandFlags.FireAndForget : CommandFlags.None);

            return(res);
        }
 public void Dispose()
 {
     try
     {
         cacheClient = null;
         GC.SuppressFinalize(this);
     }
     catch (Exception)
     {
         return;
     }
 }
コード例 #26
0
        public bool Save <T>(string key, T value)
        {
            bool isSuccess;

            serializer = new NewtonsoftSerializer();
            var redisConfiguration = RedisCachingSectionHandler.GetConfig();

            using (cacheClient = new StackExchangeRedisCacheClient(serializer, redisConfiguration))
            {
                isSuccess = cacheClient.Add <T>(key, value);
            }
            return(isSuccess);
        }
コード例 #27
0
ファイル: RedisCache.cs プロジェクト: wingfay/studio
        public static StackExchangeRedisCacheClient GetClient()
        {
            if (config == null)
            {
                config = RedisCachingSectionHandler.GetConfig();
            }



            client = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), config);

            return(client);
        }
コード例 #28
0
        /// <summary>
        ///
        /// </summary>
        public Cache()
        {
            var settings = new Tools.Settings();

            _lazyConnection = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(settings.CacheConnection));

            var serializer = new ProtobufSerializer();

            _bUseLocalCache = settings.UseLocalCache;

            _Cache = new StackExchangeRedisCacheClient(_lazyConnection.Value, serializer, "__");

            _Database = _Cache.Database;
        }
コード例 #29
0
        public RedisList(StackExchangeRedisCacheClient cacheClient, string name)
        {
            if (cacheClient == null)
            {
                throw new ArgumentNullException("CacheClient");
            }
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            this.CacheClient = cacheClient;
            this.redisKey    = string.Format(RedisKeyTemplate, name);
        }
コード例 #30
0
ファイル: Connection.cs プロジェクト: AMerkuri/YogWatch
        public void Open(RedisConfig config)
        {
            var serializer = new NewtonsoftSerializer();
            var connectionString = config.GetRedisConfiguration();

            try
            {
                _client = new StackExchangeRedisCacheClient(serializer, connectionString);
            }
            catch (Exception)
            {
                _client = null;
            }
        }
コード例 #31
0
        public DatabaseHelper()
        {
            if (_databaseType == Database.Redis)
            {
                _redis = ConnectionMultiplexer.Connect("localhost");

                RedisContext = new StackExchangeRedisCacheClient(serializer);
            }
            else if (_databaseType == Database.DynamoDb)
            {
                //AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                //DynamoDbContext = new DynamoDBContext(client);
            }
        }
コード例 #32
0
ファイル: Program.cs プロジェクト: hprez21/70532-redis-demo
        static void Main(string[] args)
        {
            var serializer =
                new NewtonsoftSerializer();
            ICacheClient client =
                new StackExchangeRedisCacheClient(serializer,
                                                  serviceUrl);

            var person = new
            {
                Name     = "Héctor Pérez",
                Subjects = new List <string> {
                    "Español",
                    "Matemáticas"
                }
            };

            client.Add("People", person,
                       DateTimeOffset.Now.AddMinutes(10));

            //ConnectionMultiplexer connection =
            //    ConnectionMultiplexer.Connect(serviceUrl);

            //IDatabase cache = connection.GetDatabase();

            //string cacheCommand = "PING";
            //Console.WriteLine(cache.Execute(cacheCommand).ToString());

            //cache.StringSet("Message", "Hola!");

            //Console.WriteLine(cache.StringGet("Message"));


            //cache.ListLeftPush("listdemo", new RedisValue[]
            //{
            //    "hola",
            //    "adiós",
            //    "Lista de Redis"
            //});

            //cache.SetAdd("setdemo", "cachedemo");

            //var setResult = cache.SetPop("setdemo");
            //Console.WriteLine(setResult);

            //connection.Dispose();
            //Console.ReadLine();
        }
コード例 #33
0
		protected CacheClientTestBase(ISerializer serializer)
		{
			Serializer = serializer;
			Sut = new StackExchangeRedisCacheClient(Serializer);
			Db = Sut.Database;
		}