Example #1
0
        public void Set_Remove()
        {
            var key   = "key";
            var value = new byte[] { 0x20, 0x20, 0x20, };

            var prefixedKey = $"{RedisCacheOptions.InstanceName}{key}";

            L1L2Cache.Set(key, value);

            Assert.Equal(
                value,
                L1L2Cache.Get(key));
            Assert.Equal(
                value,
                L1Cache.Get(prefixedKey));
            Assert.Equal(
                value,
                L2Cache.Get(key));

            L1L2Cache.Remove(key);

            Assert.Null(
                L1L2Cache.Get(key));
            Assert.Null(
                L1Cache.Get(prefixedKey));
            Assert.Null(
                L2Cache.Get(key));
        }
Example #2
0
        /// <inheritdoc />
        /// <summary>
        /// Retrieves an item from the Cache
        /// </summary>
        /// <typeparam name="T">The type of item</typeparam>
        /// <param name="key">Name of the item in cache</param>
        /// <param name="item">If the object is not found in the Cache, this will be populated</param>
        /// <returns>True if the object was found, False if not found</returns>
        public virtual bool Get <T>(string key, out T item)
        {
            // If in L1 cache, just return it
            if (Options.UseLocalCache && L1Cache.TryGetValue(key, out item))
            {
                return(true);
            }

            // Check L2 cache
            if (Options.UseDistributedCache)
            {
                byte[] bytes = null;
                try
                {
                    bytes = L2Cache.Get(key);
                }
                catch { }

                // Was not found
                if (bytes == null)
                {
                    item = default;
                    return(false);
                }

                // Object was found
                var obj = bytes.FromByteArray <L2CacheItem <T> >();
                item = obj.Item;

                // Store the object back into L1 cache
                // ReSharper disable once InvertIf
                if (Options.UseLocalCache)
                {
                    var options = new MemoryCacheEntryOptions
                    {
                        AbsoluteExpirationRelativeToNow = obj.RemainingCacheTime(),
                        Priority = obj.Priority
                    };
                    L1Cache.Set(key, item, options);
                }

                // Return it now
                return(true);
            }

            item = default;
            return(false);
        }
Example #3
0
        /// <inheritdoc />
        /// <summary>
        /// Retrieves an item from the Cache
        /// </summary>
        /// <typeparam name="T">The type of item</typeparam>
        /// <param name="key">Name of the item in cache</param>
        /// <param name="item">If the object is not found in the Cache, this will be populated</param>
        /// <returns>True if the object was found, False if not found</returns>
        public virtual bool Get <T>(string key, out T item)
        {
            byte[] bytes = null;
            try
            {
                bytes = L2Cache.Get(key);
            }
            catch { }

            // Was not found
            if (bytes == null)
            {
                item = default;
                return(false);
            }

            // Object was found
            var obj = bytes.FromByteArray <L2CacheItem <T> >();

            item = obj.Item;
            return(true);
        }
Example #4
0
        public L1L2RedisCacheTest()
        {
            var mockConnectionMultiplexer = new Mock <IConnectionMultiplexer>();

            var mockDatabase = new Mock <IDatabase>();

            mockDatabase
            .Setup(
                d => d.HashGetAll(
                    It.IsAny <RedisKey>(),
                    It.IsAny <CommandFlags>()))
            .Returns <RedisKey, CommandFlags>(
                (k, cF) =>
            {
                var key = ((string)k).Substring(
                    RedisCacheOptions.InstanceName?.Length ?? 0);
                var value = L2Cache.Get(key);
                return(new HashEntry[]
                {
                    new HashEntry("data", value),
                });
            });
            mockDatabase
            .Setup(
                d => d.KeyExists(
                    It.IsAny <RedisKey>(),
                    It.IsAny <CommandFlags>()))
            .Returns <RedisKey, CommandFlags>(
                (k, cF) => L2Cache.Get(k) != null);
            mockDatabase
            .Setup(
                d => d.KeyExistsAsync(
                    It.IsAny <RedisKey>(),
                    It.IsAny <CommandFlags>()))
            .Returns <RedisKey, CommandFlags>(
                async(k, cF) =>
            {
                var key = ((string)k).Substring(
                    RedisCacheOptions.InstanceName?.Length ?? 0);
                return(await L2Cache.GetAsync(key) != null);
            });

            var mockSubscriber = new Mock <ISubscriber>();

            mockSubscriber
            .Setup(
                s => s.Subscribe(
                    It.IsAny <RedisChannel>(),
                    It.IsAny <Action <RedisChannel, RedisValue> >(),
                    It.IsAny <CommandFlags>()));

            mockConnectionMultiplexer
            .Setup(cM => cM.GetDatabase(It.IsAny <int>(), It.IsAny <object>()))
            .Returns(mockDatabase.Object);
            mockConnectionMultiplexer
            .Setup(cM => cM.GetSubscriber(It.IsAny <object>()))
            .Returns(mockSubscriber.Object);

            L1Cache = new MemoryCache(
                Options.Create <MemoryCacheOptions>(
                    new MemoryCacheOptions()));

            L2Cache = new MemoryDistributedCache(
                Options.Create <MemoryDistributedCacheOptions>(
                    new MemoryDistributedCacheOptions()));

            var jsonSerializerOptions = Options.Create <JsonSerializerOptions>(
                new JsonSerializerOptions());

            var redisCacheOptionsAccessor = Options.Create <RedisCacheOptions>(
                new RedisCacheOptions
            {
                InstanceName = "InstanceName.",
            });

            RedisCacheOptions = redisCacheOptionsAccessor.Value;

            L1L2Cache = new L1L2RedisCache(
                mockConnectionMultiplexer.Object,
                new Func <IDistributedCache>(() => L2Cache),
                jsonSerializerOptions,
                L1Cache,
                RedisCacheOptions);
        }