Ejemplo n.º 1
1
        public RedisStorage(RedisCacheOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var builder = new ServiceCollection();
            builder.AddSingleton<IDistributedCache>(serviceProvider =>
            new RedisCache(Options.Create(options)));
            var provider = builder.BuildServiceProvider();
            Initialize((IDistributedCache)provider.GetService(typeof(IDistributedCache)));
        }
        public async Task Tests_redis_live_connection()
        {
            const string url = "http://thecatapi.com/api/images/get?format=html";

            RedisCacheOptions options = new RedisCacheOptions
            {
                Configuration = "localhost",
                InstanceName = "example-tests" + Guid.NewGuid() // create a new instance name to ensure a unique key naming to have consistent test results
            };

            var handler = new RedisCacheHandler(new HttpClientHandler(), CacheExpirationProvider.CreateSimple(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5)), options);
            using (var client = new HttpClient(handler))
            {
                for (int i = 0; i < 5; i++)
                {
                    var sw = Stopwatch.StartNew();
                    Debug.Write($"Getting data from {url}, iteration #{i + 1}...");
                    var result = await client.GetAsync(url);
                    var content = await result.Content.ReadAsStringAsync();
                    Debug.WriteLine($" completed in {sw.ElapsedMilliseconds}ms. Content was {content}.");
                }
            }

            StatsResult stats = handler.StatsProvider.GetStatistics();
            stats.Total.CacheHit.Should().Be(4);
            stats.Total.CacheMiss.Should().Be(1);
        }
Ejemplo n.º 3
0
        public RedisCache([NotNull] IOptions<RedisCacheOptions> optionsAccessor)
        {
            _options = optionsAccessor.Options;

            // This allows partitioning a single backend cache for use with multiple apps/services.
            _instance = _options.InstanceName ?? string.Empty;
        }
Ejemplo n.º 4
0
        internal IOptions <RedisCacheOptions> Configure(RedisServiceInfo si, RedisCacheConnectorOptions configuration)
        {
            RedisCacheOptions redisOptions = new RedisCacheOptions();

            UpdateOptions(configuration, redisOptions);
            UpdateOptions(si, redisOptions);
            return(new ConnectorIOptions <RedisCacheOptions>(redisOptions));
        }
Ejemplo n.º 5
0
 public RedisCacheManager()
 {
     options = new RedisCacheOptions
     {
         Configuration = "localhost",
         InstanceName  = "SampleInstance"
     };
 }
Ejemplo n.º 6
0
 public SeoFiller(
     IOptions <RedisCacheOptions> options,
     ICacheMemberSerializer serializer,
     ISetsCache setsCache)
 {
     _options    = options.Value;
     _setsCache  = setsCache;
     _serializer = serializer;
 }
Ejemplo n.º 7
0
        public StackExchangeRedisCache(IOptions <RedisCacheOptions> options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _options = options.Value;
        }
Ejemplo n.º 8
0
 public SeoService(
     ISetsCache cache,
     ICacheMemberSerializer serializer,
     IOptions <RedisCacheOptions> options)
 {
     _setsCache  = cache;
     _serializer = serializer;
     _options    = options.Value;
 }
        public void Setup()
        {
            var redisCacheOptions = new RedisCacheOptions()
            {
                Hostname = "localhost", Prefix = "cacheTests", Port = "6379",
            };

            _cache = new RedisAppCache(redisCacheOptions);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Method which resolves DNS.
        /// </summary>
        /// <param name="options"></param>
        public static void ResolveDns(this RedisCacheOptions options)
        {
            // Assume that the first part is host and port.
            var hostWithPort = options.Configuration.Substring(0, options.Configuration.IndexOf(","));
            var resolved     = TryResolveDns(hostWithPort);
            var replaced     = options.Configuration.Replace(hostWithPort, resolved);

            options.Configuration = replaced;
        }
Ejemplo n.º 11
0
        public RedisCacheService(IOptions <RedisCacheOptions> optionsAccessor) : base(optionsAccessor)
        {
            if (optionsAccessor == null)
            {
                throw new ArgumentNullException(nameof(optionsAccessor));
            }

            _options = optionsAccessor.Value;
        }
        public static IServiceCollection AddRedisCache(this IServiceCollection services, RedisCacheOptions option)
        {
            services.AddStackExchangeRedisCache(options =>
            {
                options = option;
            });

            return(services);
        }
Ejemplo n.º 13
0
        private static IDistributedCache CreateCache(string instance, string configuration)
        {
            var options = new RedisCacheOptions
            {
                Configuration = configuration,
                InstanceName  = instance
            };

            return(new RedisCache(options));
        }
Ejemplo n.º 14
0
 public static void Config(string configuration, string instanceName, int database = 0)
 {
     options = new RedisCacheOptions
     {
         Configuration = configuration,
         InstanceName  = instanceName
     };
     _database = database;
     redisConn = ConnectionMultiplexer.Connect(options.Configuration);
 }
Ejemplo n.º 15
0
        internal IOptions <RedisCacheOptions> Configure(RedisServiceInfo si, RedisCacheConnectorOptions options)
        {
            UpdateOptions(si, options);

            RedisCacheOptions redisOptions = new RedisCacheOptions();

            UpdateOptions(options, redisOptions);

            return(new ConnectorIOptions <RedisCacheOptions>(redisOptions));
        }
Ejemplo n.º 16
0
 public RedisHelper(IOptions <RedisCacheOptions> optionsAccessor)
 {
     if (optionsAccessor == null)
     {
         throw new ArgumentNullException("optionsAccessor");
     }
     _options  = optionsAccessor.Value;
     _instance = (_options.InstanceName ?? string.Empty);
     Connect();
 }
 /// <exception cref="ArgumentNullException"><paramref name="optionsAccessor"/> is <see langword="null"/></exception>
 public CSRedisCache(IOptions <RedisCacheOptions> optionsAccessor)
 {
     if (optionsAccessor == null)
     {
         throw new ArgumentNullException(nameof(optionsAccessor));
     }
     this._options     = optionsAccessor.Value;
     this._instance    = this._options.InstanceName ?? string.Empty;
     this._redisClient = new CSRedisClient(this._options.Configuration);
 }
 //这里可以做成依赖注入,但没打算做成通用类库,所以直接把连接信息直接写在帮助类里
 public RedisCacheHelper(/*RedisCacheOptions options, int database = 0*/)
 {
     options = new RedisCacheOptions();
     options.Configuration = "127.0.0.1:6379";//RedisConfig.Connection;
     options.InstanceName  = RedisConfig.InstanceName;
     _connection           = ConnectionMultiplexer.Connect(options.Configuration);
     _cache        = _connection.GetDatabase(RedisConfig.DefaultDataBase);
     _instanceName = options.InstanceName;
     _sub          = _connection.GetSubscriber();
 }
Ejemplo n.º 19
0
        private static void Main()
        {
            Console.WriteLine("Hello World!");

            RedisCacheOptions redisOptions = new RedisCacheOptions();

            redisOptions.ConfigurationOptions.

            Microsoft.Extensions.Caching.StackExchangeRedis.RedisCache redis = new Microsoft.Extensions.Caching.StackExchangeRedis.RedisCache()
        }
        public RedisCacheTests()
        {
            var logger  = new Mock <ILogger <RedisCache <string> > >();
            var options = new RedisCacheOptions {
                RedisConnectionString = ConfigurationUtils.GetConfiguration()["Redis:ConnectionString"]
            };
            var multiplexer = new RedisMultiplexer <RedisCacheOptions>(options);

            _cache = new RedisCache <string>(multiplexer, logger.Object);
        }
Ejemplo n.º 21
0
 public RedisCache(RedisMultiplexer <RedisCacheOptions> multiplexer, ILogger <RedisCache <T> > logger)
 {
     if (multiplexer is null)
     {
         throw new ArgumentNullException(nameof(multiplexer));
     }
     this.options  = multiplexer.RedisOptions;
     this.database = multiplexer.Database;
     this.logger   = logger ?? throw new ArgumentNullException(nameof(logger));
 }
        /// <summary>
        /// Add Redis caching that implements ICache<typeparamref name="T"/>
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="optionsBuilder">Redis Cache Options builder</param>
        /// <returns></returns>
        public static IIdentityServerBuilder AddRedisCaching(this IIdentityServerBuilder builder, Action <RedisCacheOptions> optionsBuilder)
        {
            var options = new RedisCacheOptions();

            optionsBuilder?.Invoke(options);
            builder.Services.AddSingleton(options);

            builder.Services.AddScoped <RedisMultiplexer <RedisCacheOptions> >();
            builder.Services.AddTransient(typeof(ICache <>), typeof(RedisCache <>));
            return(builder);
        }
Ejemplo n.º 23
0
        public override void Initialize(string store)
        {
            lock (_lock)
            {
                if (IsInitialized)
                {
                    Logger.Technical().From <RedisCache>().Debug($"Redis Cache {store} is already initialized.").Log();
                    return;
                }
                Name = store;

                if (Container.TryResolve <IKeyValueSettings>(store, out var settings))
                {
                    if (settings.Values.ContainsKey(ConnectionStringKey))
                    {
                        ConnectionString = settings.Values[ConnectionStringKey];
                    }

                    if (settings.Values.ContainsKey(DatabaseNameKey))
                    {
                        DatabaseName = settings.Values[DatabaseNameKey];
                    }

                    if (settings.Values.ContainsKey(SerializerNameKey))
                    {
                        SerializerName = settings.Values[SerializerNameKey];
                    }
                    else
                    {
                        SerializerName = store;
                    }

                    var option = new RedisCacheOptions
                    {
                        InstanceName  = DatabaseName,
                        Configuration = ConnectionString
                    };

                    DistributeCache = new StackExchangeRedis(option);

                    if (!Container.TryResolve <IObjectSerialization>(SerializerName, out var serializerFactory))
                    {
                        SerializerFactory = Container.Resolve <IObjectSerialization>();
                    }
                    else
                    {
                        SerializerFactory = serializerFactory;
                    }

                    IsInitialized = true;
                    Logger.Technical().From <RedisCache>().System($"Redis Cache {store} is initialized.").Log();
                }
            }
        }
        public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
        {
            if (optionsAccessor == null)
            {
                throw new ArgumentNullException(nameof(optionsAccessor));
            }

            _options = optionsAccessor.Value;

            // This allows partitioning a single backend cache for use with multiple apps/services.
            _instance = _options.InstanceName ?? string.Empty;
        }
Ejemplo n.º 25
0
    /// <summary>
    /// Initializes a new instance of <see cref="RedisCache"/>.
    /// </summary>
    /// <param name="optionsAccessor">The configuration options.</param>
    public RedisCache(IOptions <RedisCacheOptions> optionsAccessor)
    {
        if (optionsAccessor == null)
        {
            throw new ArgumentNullException(nameof(optionsAccessor));
        }

        _options = optionsAccessor.Value;

        // This allows partitioning a single backend cache for use with multiple apps/services.
        _instance = _options.InstanceName ?? string.Empty;
    }
Ejemplo n.º 26
0
        public RedisCacheHelper(/*RedisCacheOptions options, int database = 0*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把连接信息直接写在帮助类里
        {
            RedisCacheOptions options = new RedisCacheOptions();

            options.Configuration = "127.0.0.1:6379";
            options.InstanceName  = "test";
            int database = 0;

            _connection   = ConnectionMultiplexer.Connect(options.Configuration);
            _cache        = _connection.GetDatabase(database);
            _instanceName = options.InstanceName;
        }
Ejemplo n.º 27
0
        public RedisCacheAdapter(IConfiguration configuration)
        {
            _expiration = new TimeSpan(0, 0, configuration.GetValue <int>("cacheSeconds"));

            var options = new RedisCacheOptions()
            {
                Configuration = configuration.GetValue <string>("redisServer"),
                InstanceName  = configuration.GetValue <string>("redisInstance")
            };

            _cache = new RedisCache(Options.Create <RedisCacheOptions>(options));
        }
Ejemplo n.º 28
0
        public RedisCacheManager()
        {
            string connectionString = ApplicationSettings.TryGetValueFromAppSettings("REDIS_CONNECTIONSTRING");

            RedisCacheOptions options = new RedisCacheOptions()
            {
                Configuration = connectionString,
                InstanceName  = "master"
            };

            _distributedCache = new RedisCache(options);
        }
        public RedisCacheHelper(/*RedisCacheOptions options, int database = 0*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把连接信息直接写在帮助类里
        {
            options = new RedisCacheOptions();
            options.Configuration = CeyhConfiguration.TheRedisSettings.Connection;
            options.InstanceName  = CeyhConfiguration.TheRedisSettings.InstanceName;
            int database = CeyhConfiguration.TheRedisSettings.DefaultDatabase;

            _connection   = ConnectionMultiplexer.Connect(options.Configuration);
            _cache        = _connection.GetDatabase(database);
            _instanceName = options.InstanceName;
            _sub          = _connection.GetSubscriber();
        }
        public RedisCacheExtension(Action <RedisCacheOptions> setupAction)
        {
            if (null == setupAction)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            var options = new RedisCacheOptions();

            setupAction(options);
            _redisOption = options;
        }
        public RedisCacheManager(IConfiguration configuration)
        {
            _configuration = configuration;

            ConntectionString = configuration["ConnectionStringRedisCache:Redis"];

            options = new RedisCacheOptions()
            {
                Configuration = ConntectionString
            };

            this.redisCache = new RedisCache(options);
        }
        public static void UseRedis(
            this ConcurrencyOptionsBuilder concurrencyOptionsBuilder,
            Action<RedisCacheOptions> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            var options = new RedisCacheOptions();
            callback(options);
            UseRedis(concurrencyOptionsBuilder, options);
        }
Ejemplo n.º 33
0
 public RedisCacheIntegration(RedisCacheOptions options)
 {
     Options     = options;
     Connections = new List <Lazy <ConnectionMultiplexer> >();
     for (int i = 0; i < options.NumberOfClients; i++)
     {
         Connections.Add(new Lazy <ConnectionMultiplexer>(() =>
         {
             ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(Options.ConnectionString);
             return(connectionMultiplexer);
         }));
     }
 }
Ejemplo n.º 34
0
        public static void UseRedis(
            this ConcurrencyOptionsBuilder concurrencyOptionsBuilder,
            Action <RedisCacheOptions> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            var options = new RedisCacheOptions();

            callback(options);
            UseRedis(concurrencyOptionsBuilder, options);
        }
        public static IServiceCollection AddRedisDistributedCache <TCacheInstance>(this IServiceCollection services, Action <RedisCacheOptions> setupInner = null, Action <DistributedCacheOptions <TCacheInstance> > setup = null)
        {
            RedisCacheOptions innerOptions = new RedisCacheOptions();

            setupInner?.Invoke(innerOptions);

            DistributedCacheOptions <TCacheInstance> options = new DistributedCacheOptions <TCacheInstance>(new RedisCache(Options.Create(innerOptions)));

            setup?.Invoke(options);

            services.TryAddSingleton(options);
            services.TryAddSingleton <IDistributedCache <TCacheInstance>, DistributedCache <TCacheInstance> >();

            return(services);
        }
        public static void UseRedis(
            this ConcurrencyOptionsBuilder concurrencyOptionsBuilder,
            RedisCacheOptions options)
        {
            if (concurrencyOptionsBuilder == null)
            {
                throw new ArgumentNullException(nameof(concurrencyOptionsBuilder));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            concurrencyOptionsBuilder.ConcurrencyOptions.Storage = new RedisStorage(options);
        }
 /// <summary>
 /// Used for injecting an IMemoryCache for unit testing purposes.
 /// </summary>
 /// <param name="innerHandler">The inner handler to retrieve the content from on cache misses.</param>
 /// <param name="cacheExpirationPerHttpResponseCode">A mapping of HttpStatusCode to expiration times. If unspecified takes a default value.</param>
 /// <param name="options">Options to use to connect to Redis.</param>
 /// /// <param name="statsProvider">An <see cref="IStatsProvider"/> that records statistic information about the caching behavior.</param>
 public RedisCacheHandler(HttpMessageHandler innerHandler, IDictionary<HttpStatusCode, TimeSpan> cacheExpirationPerHttpResponseCode, RedisCacheOptions options,
     IStatsProvider statsProvider = null) : this(innerHandler, cacheExpirationPerHttpResponseCode, new RedisCache(options), statsProvider) {}