/// <summary>
        /// 根据第三方OpenId查询绑定信息
        /// </summary>
        public async Task <ExternalUserEntity> GetExternalUser(int clientId, string providerKey, bool rebuild = false)
        {
            var key = GetExternalUserRedisKey(clientId, providerKey);
            ExternalUserEntity externalUserEntity;

            if (!rebuild)
            {
                externalUserEntity = await _redisCache.GetAsync <ExternalUserEntity>(key);

                if (externalUserEntity != null)
                {
                    return(externalUserEntity);
                }
            }

            externalUserEntity = await _externalUserRepository.TableNoTracking.FirstOrDefaultAsync(
                c => c.ProviderKey == providerKey && c.ClientId == clientId);

            if (null == externalUserEntity)
            {
                return(null);
            }

            await _redisCache.AddAsync(key, externalUserEntity, TimeSpan.FromDays(15));

            return(externalUserEntity);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task <ActionObjectResult <bool> > ValidSmsAsync(string phone, string code)
        {
            var uniqueKey = GetSmsKey(phone);
            var smsCache  = await _redisCache.GetAsync <SmsCache>(uniqueKey);

            if (smsCache == null)
            {
                return(ActionObject.Ok(false, -1, "未发送验证码或验证码已超时"));
            }

            if (smsCache.ValidateCount >= 3)  //0 1  2
            {
                return(ActionObject.Ok(false, -1, "输入错误的次数超过3次,请重新获取验证码"));
            }
            if (code == smsCache.Code)
            {
                await _redisCache.KeyDeleteAsync(uniqueKey);

                return(ActionObject.Ok(true));
            }

            var timeSpan = smsCache.StartTime.AddMinutes(smsCache.ExpiresMinute) - DateTime.Now;

            if (timeSpan.TotalSeconds <= 0)
            {
                return(ActionObject.Ok(false, -1, "未发送验证码或验证码已超时"));
            }
            smsCache.ValidateCount += 1;   //更新验证次数,不延长时间
            await _redisCache.AddAsync(uniqueKey, smsCache, timeSpan);

            return(ActionObject.Ok(false, -1, "输入验证码不正确"));
        }
        public async Task <TView> UpdateAsync(string subject, Func <TView, TView> update, CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                _logger.LogInformation($"{nameof(RedisProjectionWriter<TView>)}.{nameof(UpdateAsync)} was cancelled before execution");
                cancellationToken.ThrowIfCancellationRequested();
            }

            var view = _eventDeserializer.Deserialize <TView>(await _cache.GetAsync(BuildKey(subject), cancellationToken));

            update(view);
            await _cache.SetAsync(BuildKey(subject), _eventSerializer.Serialize(view), cancellationToken);

            return(view);
        }
        public async Task <ClientEntity> GetClientByIdAsync(int clientId)
        {
            var key          = GetCacheKey(clientId);
            var clientEntity = await _redisCache.GetAsync <ClientEntity>(key);

            if (clientEntity != null)
            {
                return(clientEntity.ClientId == -1 ? null : clientEntity);
            }

            var expiry = TimeSpan.FromSeconds(5);
            var wait   = TimeSpan.FromSeconds(5);
            var retry  = TimeSpan.FromSeconds(1);

            using (var redLock = await _redisCache.CreateLockAsync(key, expiry, wait, retry))
            {
                if (!redLock.IsAcquired)
                {
                    return(null);
                }

                clientEntity = await _redisCache.GetAsync <ClientEntity>(key);

                if (clientEntity?.ClientId != -1)
                {
                    return(clientEntity);
                }

                clientEntity = await _clientRepository.TableNoTracking.FirstOrDefaultAsync(c => c.ClientId == clientId);

                if (clientEntity != null)
                {
                    await _redisCache.AddAsync(key, clientEntity);
                }
                else
                {
                    //防止不存在的clientId频繁访问数据库
                    await _redisCache.AddAsync(key, new ClientEntity { ClientId = -1 }, expiry : TimeSpan.FromMinutes(15));
                }
            }

            return(clientEntity);
        }
Example #5
0
        public async Task <bool> IsResubmitAsync(int code)
        {
            string time = await _redisCache.GetAsync <string>(code.ToString());

            if (string.IsNullOrEmpty(time))
            {
                await _redisCache.SetAsync(code.ToString(), "Unduplicate", TimeSpan.FromSeconds(_options.DuplicateInterval));

                return(false);
            }

            return(true);
        }
Example #6
0
        private static async Task CQRedisTest()
        {
            string      key        = "key";
            string      token      = "token";
            IRedisCache redisCache = _provider.GetRequiredService <IRedisCache>();
            await redisCache.SetAsync(key, token);

            string r = await redisCache.GetAsync <string>(key);

            bool take = await redisCache.LockTakeAsync(key, token, TimeSpan.FromSeconds(500));

            bool take2 = await redisCache.LockTakeAsync(key, token, TimeSpan.FromSeconds(500));

            await redisCache.LockReleaseAsync(key, token);
        }
Example #7
0
        public async Task Handle(PingNotificationMessage notification, CancellationToken cancellationToken)
        {
            MonitoringHistoryDto history = null;

            //TODO  extension
            var cacheKey =
                $"{notification.EndPointId}-{nameof(SensorType.Ping)}-{DateTime.Now.ToString(@"yyyy-MM-dd")}";

            history = await _cache.GetAsync <MonitoringHistoryDto>(cacheKey) ?? new MonitoringHistoryDto();

            if (history.LastStatus != notification.PingSuccess)
            {
                await Notify(notification, cancellationToken);
            }

            history.AddCheckEvent(DateTime.Now, notification.PingSuccess);
            await _cache.SetAsync(cacheKey, history);
        }
Example #8
0
        public async Task Handle(DoPageLoadMessage notification, CancellationToken cancellationToken)
        {
            var cacheKey  = $"{notification.EndPointId}-{nameof(SensorType.PageLoad)}";
            var operation = await _cache.GetAsync <OngoingOperationDto>(cacheKey);

            if (operation != null)
            {
                if ((DateTime.Now - operation.StartDate).TotalMinutes <= 1)
                {
                    return;
                }
            }
            else
            {
                await _cache.SetAsync(cacheKey, new OngoingOperationDto(DateTime.Now));
            }

            var networkavailability = true;

            var urlResult = WebSiteUtil.IsUrlAlive(notification.PageUrl);

            if (urlResult == false) // check network availability
            {
                networkavailability = PingUtil.Ping("8.8.8.8");
            }

            if (networkavailability == false)
            {
                //TODO Notify about  connection
            }
            else
            {
                await _mediator.Publish(new PageLoadNotificationMessage
                {
                    PageUrl      = notification.PageUrl,
                    EmailNotify  = notification.EmailNotify,
                    EndPointId   = notification.EndPointId,
                    MobileNotify = notification.MobileNotify,
                    LoadSuccess  = urlResult
                }, cancellationToken);
            }
        }
Example #9
0
        public async Task Handle(DoPingMessage notification, CancellationToken cancellationToken)
        {
            var cacheKey  = $"{notification.EndPointId}-{nameof(SensorType.Ping)}";
            var operation = await _cache.GetAsync <OngoingOperationDto>(cacheKey);

            if (operation != null)
            {
                if ((DateTime.Now - operation.StartDate).TotalMinutes <= 1)
                {
                    return;
                }
            }
            else
            {
                await _cache.SetAsync(cacheKey, new OngoingOperationDto(DateTime.Now));
            }

            var networkavailability = true;

            var pingResult = PingUtil.Ping(notification.IpAddress);

            if (pingResult == false) // IS Network availability
            {
                networkavailability = PingUtil.Ping("8.8.8.8");
            }

            if (networkavailability == false)
            {
                //TODO Notify about  connection
            }
            else
            {
                await _mediator.Publish(new PingNotificationMessage
                {
                    IpAddress    = notification.IpAddress,
                    EmailNotify  = notification.EmailNotify,
                    EndPointId   = notification.EndPointId,
                    MobileNotify = notification.MobileNotify,
                    PingSuccess  = pingResult
                }, cancellationToken);
            }
        }
Example #10
0
        private async Task <(string, JwtToken)> GetCacheToken()
        {
            var key = $"client_credentials:{_appSettings.ClientId}";

            var tokenResult = await _redisCache.GetAsync <JwtToken>(key);

            if (!string.IsNullOrWhiteSpace(tokenResult?.AccessToken))
            {
                return("", tokenResult);
            }

            var(tokenerror, result) = await _authorizeTokenClient.GetToken();

            if (!string.IsNullOrEmpty(tokenerror))
            {
                return(tokenerror, null);
            }

            await _redisCache.AddAsync(key, result, TimeSpan.FromSeconds(int.Parse(result.ExpiresIn) - 300));

            return("", result);
        }
Example #11
0
 /// <summary>
 /// Get
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key"></param>
 /// <returns></returns>
 public async Task <T> GetAsync <T>(string key)
 {
     return(await _cache.GetAsync <T>(key));
 }
Example #12
0
 public async Task <T> GetAsync(string id)
 {
     return(await _cache.GetAsync <T>(new RateLimitCacheKey(id)));
 }