Esempio n. 1
0
        internal TableCacheEntity(string partitionKey, string rowKey, byte[] data = null, DistributedCacheEntryOptions options = null)
            : base(partitionKey, rowKey)
        {
            DateTimeOffset utcNow = DateTimeOffset.UtcNow;

            if (options?.AbsoluteExpirationRelativeToNow != null)
            {
                AbsoluteExpiration = utcNow.Add(options.AbsoluteExpirationRelativeToNow.Value);
            }
            else if (options?.AbsoluteExpiration != null)
            {
                if (options.AbsoluteExpiration <= utcNow)
                {
                    throw new ArgumentOutOfRangeException(nameof(options.AbsoluteExpiration), options.AbsoluteExpiration.Value, "Absolute expiration value must be in the future.");
                }

                AbsoluteExpiration = options.AbsoluteExpiration;
            }

            Data = data;
            SlidingExpiration = options?.SlidingExpiration;
            LastAccessedTime  = utcNow;
        }
 public async Task SetManyAsync(IEnumerable <KeyValuePair <string, byte[]> > items, DistributedCacheEntryOptions options, CancellationToken token = default)
 {
     foreach (var item in items)
     {
         await SetAsync(item.Key, item.Value, options, token);
     }
 }
Esempio n. 3
0
        public static void Set <T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options)
        {
            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, value);
                bytes = memoryStream.ToArray();
            }

            cache.Set(key, bytes, options);
        }
 /// <summary>
 /// This method is used to set an object into cache as a JSON converted string.
 /// </summary>
 /// <param name="cache">Contains the cache to extend.</param>
 /// <param name="key">Contains the key of the cache item to set.</param>
 /// <param name="item">Contains the item to convert to JSON.</param>
 /// <param name="options">Contains an optional cache entry options.</param>
 /// <param name="token">Contains an optional cancellation token.</param>
 /// <returns></returns>
 public static async Task SetJsonAsync(this IDistributedCache cache, string key, object item, DistributedCacheEntryOptions options = null, CancellationToken token = default)
 {
     string content = JsonConvert.SerializeObject(item);
     await cache.SetStringAsync(key, content, options, token);
 }
Esempio n. 5
0
 public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// 获取指定键的缓存项,不存在则从指定委托获取,并回存到缓存中再返回
        /// </summary>
        public static TResult Get <TResult>(this IDistributedCache cache, string key, Func <TResult> getFunc, DistributedCacheEntryOptions options = null)
        {
            TResult result = cache.Get <TResult>(key);

            if (!Equals(result, default(TResult)))
            {
                return(result);
            }
            result = getFunc();
            if (Equals(result, default(TResult)))
            {
                return(default(TResult));
            }
            cache.Set(key, result, options);
            return(result);
        }
        /// <summary>
        /// 异步将对象存入缓存中
        /// </summary>
        public static async Task SetAsync(this IDistributedCache cache, string key, object value, DistributedCacheEntryOptions options = null)
        {
            Check.NotNullOrEmpty(key, nameof(key));
            Check.NotNull(value, nameof(value));

            string json = value.ToJsonString();

            if (options == null)
            {
                await cache.SetStringAsync(key, json);
            }
            else
            {
                await cache.SetStringAsync(key, json, options);
            }
        }
Esempio n. 8
0
 public static async Task SetObject(
     this IDistributedCache distributedCache,
     string key, object value, DistributedCacheEntryOptions options)
 {
     await distributedCache.SetAsync(key, value.ToByteArray(), options);
 }
Esempio n. 9
0
 public static async Task SetObjectAsync(this IDistributedCache cache, string key, object value,
                                         DistributedCacheEntryOptions options)
 {
     var json = JsonConvert.SerializeObject(value, _serializerSettings);
     await cache.SetStringAsync(key, json, options);
 }
Esempio n. 10
0
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     return(base.SetAsync(key, value, new DistributedCacheEntryOptions()));
 }
 public DistributedCacheValueTypeExtensionsTest()
 {
     _cache  = new FakeDistributedCache();
     _option = new DistributedCacheEntryOptions();
 }
Esempio n. 12
0
 public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     base.Set(key, value, new DistributedCacheEntryOptions());
 }
Esempio n. 13
0
        public void Intercept(IInvocation invocation)
        {
            Console.WriteLine("执行前...");

            // 判断当前方法是否包含 IgnoreCache 特性
            var method       = invocation.GetConcreteMethod();                 // 调用的具体方法,接口、具体类
            var targetMethod = invocation.GetConcreteMethodInvocationTarget(); // 获取具体的调用目标方法,也就是实际执行的方法

            // 忽略缓存
            var ignoreAttr = this.GetAttribute <IgnoreCacheAttribute>(method, targetMethod);

            if (ignoreAttr != null)
            {
                Console.WriteLine("忽略缓存...");
                // 执行原本方法
                invocation.Proceed();
                return;
            }

            Console.WriteLine("读取本地缓存...");
            // 本地缓存配置
            var memoryOptions = this.GetAttribute <MemoryCacheOptionsAttribute>(method, targetMethod);
            // 生成缓存 key
            var memoryCacheKey = this.GenericCacheKey(invocation, memoryOptions.KeyPrefix);

            // Redis缓存获取
            var redisOptions = this.GetAttribute <RedisCacheOptionsAttribute>(method, targetMethod);

            // 读取本地缓存
            var cacheValue = _memoryCache.Get(memoryCacheKey);

            if (cacheValue == null)
            {
                Console.WriteLine("读取Redis缓存...");
                // 生成缓存 key
                var redisCacheKey = this.GenericCacheKey(invocation, redisOptions.KeyPrefix);
                cacheValue = _distributedCache.Get(redisCacheKey);
            }

            if (cacheValue != null)
            {
                Console.WriteLine("读取缓存...");
                //将当前获取到的缓存值,赋值给当前执行方法
                invocation.ReturnValue = cacheValue;
                return;
            }

            // 执行原本方法
            invocation.Proceed();

            //存入缓存
            if (!string.IsNullOrWhiteSpace(memoryCacheKey))
            {
                Console.WriteLine("写入本地缓存...");
                // 写入本地缓存
                var entryOptions = new MemoryCacheEntryOptions()
                                   .SetSize(1)
                                   // (TimeSpan.FromSeconds((double)memoryOptions.AbsoluteExpiration))
                                   .SetSlidingExpiration(TimeSpan.FromSeconds((double)memoryOptions.SlidingExpiration));
                if (memoryOptions.AbsoluteExpiration > 0)
                {
                    entryOptions.SetAbsoluteExpiration(DateTime.Now.AddSeconds((double)memoryOptions.AbsoluteExpiration));
                }
                _memoryCache.Set(memoryCacheKey, invocation.ReturnValue, entryOptions);

                Console.WriteLine("写入Redis缓存...");
                // 写入Redis缓存
                var redisEntryOptions = new DistributedCacheEntryOptions()
                {
                    SlidingExpiration = TimeSpan.FromSeconds((double)redisOptions.SlidingExpiration)
                };
                if (redisOptions.AbsoluteExpiration > 0)
                {
                    redisEntryOptions.SetAbsoluteExpiration(DateTime.Now.AddSeconds((double)redisOptions.AbsoluteExpiration));
                }
                _distributedCache.SetString(memoryCacheKey, System.Text.Json.JsonSerializer.Serialize(invocation.ReturnValue), redisEntryOptions);
            }
            Console.WriteLine("执行后...");
        }
 public static Task SetAsync <TValue>(this IDistributedCache cache, TValue value, string[] keys,
                                      DistributedCacheEntryOptions options, CancellationToken cancellationToken = new())
Esempio n. 15
0
        private static DateTimeOffset?GetAbsoluteExpiration(DateTimeOffset creationTime, DistributedCacheEntryOptions options)
        {
            if (options.AbsoluteExpiration.HasValue && options.AbsoluteExpiration <= creationTime)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(DistributedCacheEntryOptions.AbsoluteExpiration),
                          options.AbsoluteExpiration.Value,
                          "The absolute expiration value must be in the future.");
            }
            var absoluteExpiration = options.AbsoluteExpiration;

            if (options.AbsoluteExpirationRelativeToNow.HasValue)
            {
                absoluteExpiration = creationTime + options.AbsoluteExpirationRelativeToNow;
            }

            return(absoluteExpiration);
        }
Esempio n. 16
0
 public async static Task SetAsync <T>(this IDistributedCache distributedCache, string key, T value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
 {
     await distributedCache.SetAsync(key, value.ToByteArray(), options, token);
 }
Esempio n. 17
0
 public RedisCacheManager(IDistributedCache cache, DistributedCacheEntryOptions options, RedisConnection redisConnection)
 {
     _redisConnection  = redisConnection;
     _options          = options;
     _distributedCache = cache;
 }
Esempio n. 18
0
 public CacheServicesDistributedCache(IDistributedCache distributedCache, DistributedCacheEntryOptions cacheOptions)
 {
     _distributedCache = distributedCache;
     _cacheOptions     = cacheOptions;
 }
        /// <summary>
        /// 异步获取指定键的缓存项,不存在则从指定委托获取,并回存到缓存中再返回
        /// </summary>
        public static async Task <TResult> GetAsync <TResult>(this IDistributedCache cache, string key, Func <Task <TResult> > getAsyncFunc, DistributedCacheEntryOptions options = null)
        {
            TResult result = await cache.GetAsync <TResult>(key);

            if (!Equals(result, default(TResult)))
            {
                return(result);
            }
            result = await getAsyncFunc();

            if (Equals(result, default(TResult)))
            {
                return(default(TResult));
            }
            await cache.SetAsync(key, result, options);

            return(result);
        }
        public static Task SetAsync <T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options, CancellationToken cancellationToken = default)
        {
            var serialized = JsonSerializer.Serialize(value);
            var bytes      = Encoding.UTF8.GetBytes(serialized);

            return(cache.SetAsync(key, bytes, options, cancellationToken));
        }
        /// <summary>
        /// This method is used to set an object into cache as a JSON converted string.
        /// </summary>
        /// <param name="cache">Contains the cache to extend.</param>
        /// <param name="key">Contains the key of the cache item to set.</param>
        /// <param name="item">Contains the item to convert to JSON.</param>
        /// <param name="options">Contains an optional cache entry options.</param>
        /// <returns></returns>
        public static void SetJson(this IDistributedCache cache, string key, object item, DistributedCacheEntryOptions options = null)
        {
            string content = JsonConvert.SerializeObject(item);

            cache.SetString(key, content, options);
        }
Esempio n. 22
0
 public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     SetAsync(key, value, options).Wait();
 }
        }                                                                                        //TODO: use a configurator interface instead?

        public PlusDistributedCacheOptions()
        {
            CacheConfigurators      = new List <Func <string, DistributedCacheEntryOptions> >();
            GlobalCacheEntryOptions = new DistributedCacheEntryOptions();
            KeyPrefix = "";
        }
Esempio n. 24
0
        /// <summary>
        /// Configures depdendency injection.
        /// </summary>
        /// <param name="services">The service collection.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            switch (NeonBlazorProxyService.Config.Cache.Backend)
            {
            case CacheType.InMemory:

                services.AddDistributedMemoryCache();
                break;

            case CacheType.Redis:

                services.AddStackExchangeRedisCache(options => { NeonBlazorProxyService.Config.Cache.Redis.GetOptions(); });
                break;

            default:

                services.AddDistributedMemoryCache();
                break;
            }

            services.AddSingleton(NeonBlazorProxyService);
            services.AddSingleton(NeonBlazorProxyService.Config);
            services.AddSingleton <INeonLogger>(NeonBlazorProxyService.Log);
            services.AddSingleton(NeonBlazorProxyService.DnsClient);
            services.AddHealthChecks();
            services.AddHttpForwarder();
            services.AddHttpClient();
            services.AddAllPrometheusMetrics();

            // Http client for Yarp.

            services.AddSingleton <HttpMessageInvoker>(
                serviceProvider =>
            {
                return(new HttpMessageInvoker(new SocketsHttpHandler()
                {
                    UseProxy = false,
                    AllowAutoRedirect = false,
                    AutomaticDecompression = DecompressionMethods.None,
                    UseCookies = false,
                    ActivityHeadersPropagator = new ReverseProxyPropagator(DistributedContextPropagator.Current)
                }));
            });

            // Cookie encryption cipher.

            services.AddSingleton(NeonBlazorProxyService.AesCipher);

            var cacheOptions = new DistributedCacheEntryOptions()
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(NeonBlazorProxyService.Config.Cache.DurationSeconds)
            };

            services.AddSingleton(cacheOptions);

            services.AddSingleton <SessionTransformer>(
                serviceProvider =>
            {
                return(new SessionTransformer(serviceProvider.GetService <IDistributedCache>(), NeonBlazorProxyService.Log, cacheOptions, NeonBlazorProxyService.AesCipher));
            });

            services.AddControllers()
            .AddNeon();
        }
Esempio n. 25
0
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
 {
     throw new NotImplementedException();
 }
 public override async Task <IEnumerable <Price> > GetOrSetValueAsync(string key, Func <Task <IEnumerable <Price> > > valueDelegate,
                                                                      DistributedCacheEntryOptions options = null)
 {
     //call the base class' method with the clarified caching options
     return(await base.GetOrSetValueAsync(key, valueDelegate, options));
 }
Esempio n. 27
0
        public static Task SetAsync <T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options)
        {
            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, value);
                bytes = memoryStream.ToArray();
            }

            key.Replace(" ", string.Empty);

            return(cache.SetAsync(key, bytes, options));
        }
Esempio n. 28
0
 private static long?GetExpirationInSeconds(DateTimeOffset creationTime, DateTimeOffset?absoluteExpiration, DistributedCacheEntryOptions options)
 {
     if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue)
     {
         return((long)Math.Min(
                    (absoluteExpiration.Value - creationTime).TotalSeconds,
                    options.SlidingExpiration.Value.TotalSeconds));
     }
     else if (absoluteExpiration.HasValue)
     {
         return((long)(absoluteExpiration.Value - creationTime).TotalSeconds);
     }
     else if (options.SlidingExpiration.HasValue)
     {
         return((long)options.SlidingExpiration.Value.TotalSeconds);
     }
     return(null);
 }
Esempio n. 29
0
        private void CreateBulkInsert(DbCommand cmd, IEnumerable <KeyValuePair <string, byte[]> > keyValues, DistributedCacheEntryOptions options)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(DbCommands.Commands[(int)Operation.BulkInsert]);
            int i = 0;

            foreach (var pair in keyValues)
            {
                sb.Append($"(@key{i}, @value{i}, @expiry, @renewal),");
                cmd.Parameters.AddWithValue($"@key{i}", pair.Key);
                cmd.Parameters.AddWithValue($"@value{i}", pair.Value);
                i++;
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append(";");

            AddExpirationParameters(cmd, options);

            cmd.CommandText = sb.ToString();
        }
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default) =>
 _distributedCache.SetAsync(key, value, options, token);