コード例 #1
0
        public async ValueTask <CacheItem> AddAsync(CacheItem obj)
        {
            if (!obj.IsValidKey())
            {
                throw new InvalidCacheKeyException("object to cache is invalid key not informed!");
            }
            var cacheItem = await _provider.GetAsync(obj.Key);

            if (cacheItem != null)
            {
                throw new DuplicateCacheKeyException($"object with key {obj.Key} already exists!");
            }
            return(await _provider.AddAsync(obj));
        }
コード例 #2
0
        /// <summary>
        /// Proceeds the able async.
        /// </summary>
        /// <returns>The able async.</returns>
        /// <param name="context">Context.</param>
        /// <param name="next">Next.</param>
        private async Task ProceedAbleAsync(AspectContext context, AspectDelegate next)
        {
            var attribute = context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) as EasyCachingAbleAttribute;

            if (attribute != null)
            {
                var cacheKey   = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);
                var cacheValue = await CacheProvider.GetAsync <object>(cacheKey);

                if (cacheValue.HasValue)
                {
                    context.ReturnValue = cacheValue.Value;
                }
                else
                {
                    // Invoke the method if we don't have a cache hit
                    await next(context);

                    if (!string.IsNullOrWhiteSpace(cacheKey) && context.ReturnValue != null)
                    {
                        await CacheProvider.SetAsync(cacheKey, context.ReturnValue, TimeSpan.FromSeconds(attribute.Expiration));
                    }
                }
            }
            else
            {
                // Invoke the method if we don't have EasyCachingAbleAttribute
                await next(context);
            }
        }
        public async Task ThenIShouldGetTheCachedItem()
        {
            //Arrange
            const string key  = "test";
            const string item = "payload";

            _cache.Setup(x => x.ExistsAsync(It.IsAny <string>())).ReturnsAsync(true);
            _cache.Setup(x => x.GetCustomValueAsync <string>(key)).ReturnsAsync(item);

            //Act
            var result = await _provider.GetAsync <string>(key);

            //Assert
            Assert.AreEqual(item, result);
            _cache.Verify(x => x.ExistsAsync(key), Times.Once);
            _cache.Verify(x => x.GetCustomValueAsync <string>(key), Times.Once);
        }
コード例 #4
0
        private async Task ProcessGetOrCreateAsync(AspectContext context, AspectDelegate next)
        {
            if (GetMethodAttributes(context.ServiceMethod) is EniymCacheGetOrCreateAttribute attribute)
            {
                if (string.IsNullOrEmpty(attribute.Template))
                {
                    throw new ArgumentNullException($"please set the cache key '{nameof(attribute.Template)}'");
                }

                var returnType = context.IsAsync()
                    ? context.ServiceMethod.ReturnType.GetGenericArguments().First()
                    : context.ServiceMethod.ReturnType;

                var cacheKey = KeyGenerator.GetCacheKey(context, attribute.Template);
                Logger.LogInformation($"KeyGenerator.GetCacheKey: '{cacheKey}'");

                object cacheValue = null;
                try
                {
                    cacheValue = await CacheProvider.GetAsync(cacheKey, returnType);
                }
                catch
                {
                    Logger.LogError($"An error occurred while reading cache '{cacheKey}'.");
                    cacheValue = null;
                }

                if (cacheValue != null)
                {
                    context.ReturnValue = context.IsAsync()
                        ? TaskResultMethod
                                          .GetOrAdd(returnType,
                                                    t => typeof(Task).GetMethods()
                                                    .First(p => p.Name == "FromResult" && p.ContainsGenericParameters)
                                                    .MakeGenericMethod(returnType)).Invoke(null, new object[] { cacheValue })
                        : cacheValue;
                }
                else
                {
                    await next(context);

                    var returnValue = context.IsAsync()
                        ? await context.UnwrapAsyncReturnValue()
                        : context.ReturnValue;

                    if (returnValue != null)
                    {
                        await CacheProvider.SetAsync(cacheKey, returnValue, attribute.CacheSeconds);
                    }
                }
            }
            else
            {
                await next(context);
            }
        }
コード例 #5
0
        /// <summary>
        /// Proceeds the able async.
        /// </summary>
        /// <returns>The able async.</returns>
        /// <param name="context">Context.</param>
        /// <param name="next">Next.</param>
        private async Task ProceedAbleAsync(AspectContext context, AspectDelegate next)
        {
            if (context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) is EasyCachingAbleAttribute attribute)
            {
                var returnType = context.IsAsync()
                        ? context.ServiceMethod.ReturnType.GetGenericArguments().First()
                        : context.ServiceMethod.ReturnType;

                var cacheKey = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);

                object cacheValue = await CacheProvider.GetAsync(cacheKey, returnType);

                if (cacheValue != null)
                {
                    if (context.IsAsync())
                    {
                        //#1
                        //dynamic member = context.ServiceMethod.ReturnType.GetMember("Result")[0];
                        //dynamic temp = System.Convert.ChangeType(cacheValue.Value, member.PropertyType);
                        //context.ReturnValue = System.Convert.ChangeType(Task.FromResult(temp), context.ServiceMethod.ReturnType);

                        //#2
                        context.ReturnValue =
                            TypeofTaskResultMethod.GetOrAdd(returnType, t => typeof(Task).GetMethods().First(p => p.Name == "FromResult" && p.ContainsGenericParameters).MakeGenericMethod(returnType)).Invoke(null, new object[] { cacheValue });
                    }
                    else
                    {
                        //context.ReturnValue = System.Convert.ChangeType(cacheValue.Value, context.ServiceMethod.ReturnType);
                        context.ReturnValue = cacheValue;
                    }
                }
                else
                {
                    // Invoke the method if we don't have a cache hit
                    await next(context);

                    if (context.IsAsync())
                    {
                        //get the result
                        var returnValue = await context.UnwrapAsyncReturnValue();

                        await CacheProvider.SetAsync(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration));
                    }
                    else
                    {
                        await CacheProvider.SetAsync(cacheKey, context.ReturnValue, TimeSpan.FromSeconds(attribute.Expiration));
                    }
                }
            }
            else
            {
                // Invoke the method if we don't have EasyCachingAbleAttribute
                await next(context);
            }
        }
コード例 #6
0
        /// <summary>
        /// Оповестить клиента о принятом звонке
        /// </summary>
        /// <param name="operatorId"></param>
        /// <param name="callId"></param>
        /// <returns></returns>
        public async Task NotifyAboutAcceptedCall(Guid userId, Guid callId)
        {
            var connectionId = await _cacheProvider.GetAsync <string>(GisOperatorsCacheCollectionName, userId.ToString());

            if (string.IsNullOrWhiteSpace(connectionId))
            {
                _logger.Warning($"Не найден оператор с {nameof(userId)}: {userId}");
            }
            else
            {
                await _gisHubContext.Clients.Client(connectionId).SendAsync("OnCallAccepted", callId);
            }
        }
コード例 #7
0
        /// <summary>
        /// Proceeds the able async.
        /// </summary>
        /// <returns>The able async.</returns>
        /// <param name="context">Context.</param>
        /// <param name="next">Next.</param>
        private async Task ProceedAbleAsync(AspectContext context, AspectDelegate next)
        {
            var attribute = context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) as EasyCachingAbleAttribute;

            if (attribute != null)
            {
                var cacheKey   = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);
                var cacheValue = await CacheProvider.GetAsync <object>(cacheKey);

                if (cacheValue.HasValue)
                {
                    if (context.IsAsync())
                    {
                        //#1
                        dynamic member = context.ServiceMethod.ReturnType.GetMember("Result")[0];
                        dynamic temp   = System.Convert.ChangeType(cacheValue.Value, member.PropertyType);
                        context.ReturnValue = System.Convert.ChangeType(Task.FromResult(temp), context.ServiceMethod.ReturnType);

                        //#2
                        //...
                    }
                    else
                    {
                        context.ReturnValue = System.Convert.ChangeType(cacheValue.Value, context.ServiceMethod.ReturnType);
                    }
                }
                else
                {
                    // Invoke the method if we don't have a cache hit
                    await next(context);

                    if (context.IsAsync())
                    {
                        //get the result
                        var returnValue = await context.UnwrapAsyncReturnValue();

                        await CacheProvider.SetAsync(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration));
                    }
                    else
                    {
                        await CacheProvider.SetAsync(cacheKey, context.ReturnValue, TimeSpan.FromSeconds(attribute.Expiration));
                    }
                }
            }
            else
            {
                // Invoke the method if we don't have EasyCachingAbleAttribute
                await next(context);
            }
        }
コード例 #8
0
        /// <summary>
        /// Оператор вышел из системы
        /// </summary>
        private async Task OperatorDisconnect()
        {
            var userId = await _cacheProvider.GetAsync <Guid>(ActiveOperatorsCacheCollectionName, Context.ConnectionId);

            if (userId == default)
            {
                _logger.Warning($"OperatorDisconnect. UserId not found in cache on SignalR disconnection");
                return;
            }

            _logger.Debug($"Successfully received extension from cache while disconnecting client from SignalR userId '{userId}' ");
            await _userService.ChangeActivityStatus(userId, false);

            await _cacheProvider.RemoveAsync(ActiveOperatorsCacheCollectionName, Context.ConnectionId);

            await _callManagementService.EndAllUserCalls(userId);

            _logger.Debug($"A notification was sent that the user with Id '{userId}' disconnected from SignalR hub");
        }
コード例 #9
0
 public async Task <CacheItem> GetAsync() => await provider.GetAsync("1");