public RedisResult <RedisIsMasterDownInfo> IsMasterDownByAddr(string ipAddress, int port, string runId)
        {
            if (ipAddress.IsEmpty())
            {
                throw new ArgumentNullException("ipAddress");
            }

            if (runId.IsEmpty())
            {
                throw new ArgumentNullException("runId");
            }

            var raw = ExpectArray(RedisCommandList.Sentinel, RedisCommandList.SentinelIsMasterDownByAddr,
                                  ipAddress.ToBytes(), port.ToBytes(),
                                  ((long)RedisCommon.EpochNow()).ToBytes(), runId.ToBytes());

            if (!ReferenceEquals(raw, null))
            {
                var rawValue = raw.Value;
                if (!ReferenceEquals(rawValue, null) && rawValue.Type == RedisRawObjectType.Array)
                {
                    var info = RedisIsMasterDownInfo.Parse(rawValue);
                    return(new RedisResult <RedisIsMasterDownInfo>(info));
                }
            }
            return(new RedisResult <RedisIsMasterDownInfo>(RedisIsMasterDownInfo.Empty));
        }
Example #2
0
 public virtual uint GetCRCHashCode()
 {
     if (!m_CRCHash.HasValue)
     {
         m_CRCHash = RedisCommon.CRC32ChecksumOf(ToString().ToBytes());
     }
     return(m_CRCHash.Value);
 }
Example #3
0
        public Dictionary <string, HashSet <string> > ConvertToDictionary(List <TModel> list)
        {
            Dictionary <string, HashSet <string> > dictionary = new Dictionary <string, HashSet <string> >();
            object propertyValue    = null;
            string propertyValueStr = "";

            foreach (var property in redisIndexProperties)
            {
                foreach (var model in list)
                {
                    propertyValue = property.GetValue(model, null);

                    if (propertyValue == null)
                    {
                        continue;
                    }

                    propertyValueStr = propertyValue.ToString();

                    if (string.IsNullOrWhiteSpace(propertyValueStr))
                    {
                        continue;
                    }

                    bool   isExisted = false;
                    string key       = GetKey(property.Name, propertyValueStr);
                    string value     = RedisCommon.GetPrimaryKeysValuesStr <TModel>(model, primaryKeysProperties);

                    if (string.IsNullOrEmpty(value))
                    {
                        continue;
                    }

                    foreach (var item in dictionary)
                    {
                        if (item.Key == key)
                        {
                            item.Value.Add(value);
                            isExisted = true;
                            break;
                        }
                    }

                    if (!isExisted)
                    {
                        dictionary.Add(key, new HashSet <string>(new List <string>()
                        {
                            value
                        }));
                    }

                    propertyValue    = null;
                    propertyValueStr = null;
                }
            }

            return(dictionary);
        }
 public UserController(VerifyCodeHelper verifyCodeHelper,
                       IConfiguration configuration,
                       ChangReadContext changReadContext,
                       RedisCommon redisCommon) : base(configuration)
 {
     this._verifyCodeHelper = verifyCodeHelper;
     this._dbContext        = changReadContext;
     this._redisCommon      = redisCommon;
 }
        /// <summary>
        /// 方法执行前
        /// </summary>
        /// <param name="context"></param>
        public override async System.Threading.Tasks.Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 判断是否忽略验证
            if (context.ActionDescriptor is ControllerActionDescriptor cad)
            {
                var controleIgnor = cad.ControllerTypeInfo.GetCustomAttributes(inherit: true).Any(x => x is IgnorTokenAttribute || x is InnerServiceAttribute || x is AllowAnonymousAttribute);
                if (controleIgnor)
                {
                    return;
                }
                var actionIgnor = cad.MethodInfo.GetCustomAttributes(inherit: true).Any(x => x is IgnorTokenAttribute || x is InnerServiceAttribute || x is AllowAnonymousAttribute);
                if (actionIgnor)
                {
                    return;
                }
            }

            ApiResultModel <string> apiResult = null;
            var path   = context.HttpContext.Request.Path;
            var source = context.HttpContext.Request.Headers[SourceKey];//请求来源为微信时,不做token验证

            if (string.IsNullOrEmpty(source) || source != "wx")
            {
                var token = context.HttpContext.Request.Headers[TokenKey];
                if (!string.IsNullOrEmpty(token))
                {
                    //不存在该缓存键
                    if (!RedisClient.Exists(RedisDatabase.DB_UserService, RedisCommon.GetTokenKey(token)))
                    {
                        apiResult = new ApiResultModel <string>()
                        {
                            Code = ApiResultCode.UserInvalid
                        };
                        context.Result = new JsonResult(apiResult);
                        return;
                    }
                }
                else
                {
                    apiResult = new ApiResultModel <string>()
                    {
                        Code = ApiResultCode.NoToken
                    };
                    context.Result = new JsonResult(apiResult);

                    //日志
                    Net4Logger.Error(path, "非法请求(无token)");
                }
            }
            await base.OnActionExecutionAsync(context, next);
        }
Example #6
0
        public bool UpdateHistoryWeatherToMssql()
        {
            RedisCommon redis = new RedisCommon();

            try
            {
                redis.CtrlHistoricalWeather();
            }
            catch (Exception e)
            {
                log.ErrorFormat("MSSQL同步Redis发生异常:{0}", e);
                return(false);
            }
            return(true);
        }
Example #7
0
        public List <string> GetKeys(TModel model)
        {
            List <string> keys = new List <string>();

            foreach (var indexProperty in redisIndexProperties)
            {
                string value = RedisCommon.GetPropertyValueStr <TModel>(model, indexProperty);

                if (!string.IsNullOrEmpty(value))
                {
                    keys.Add(GetKey(indexProperty.Name, value));
                }
            }

            return(keys);
        }
Example #8
0
        public void SaveData(List <TModel> list)
        {
            Dictionary <string, string> dictionary = new Dictionary <string, string>();

            foreach (var model in list)
            {
                string field = RedisCommon.GetPrimaryKeysValuesStr <TModel>(model, primaryKeysProperties);

                if (!string.IsNullOrEmpty(field))
                {
                    dictionary.Add(field, JsonSerializer.SerializeToString <TModel>(model));
                }
            }

            redisHelper.HSet(GetKey(), dictionary);
        }
Example #9
0
        public string GetKey(TModel model)
        {
            string value = "";

            if (primaryKeysProperties.Count == 0)
            {
                value = RedisCommon.WildCard;
            }
            else if (primaryKeysProperties.Count == 1)
            {
                value = RedisCommon.GetPropertyValueStr <TModel>(model, primaryKeysProperties[0], RedisCommon.WildCard);
            }
            else
            {
                value = RedisCommon.GetPropertiesKeysValuesStr <TModel>(model, primaryKeysProperties, RedisCommon.WildCard);
            }

            return(GetKey(value));
        }
        public RedisResult <RedisIsMasterDownInfo> IsMasterDownByAddr(string ipAddress, int port, string runId)
        {
            if (ipAddress.IsEmpty())
            {
                throw new ArgumentNullException("ipAddress");
            }

            if (runId.IsEmpty())
            {
                throw new ArgumentNullException("runId");
            }

            var array = ExpectArray(new RedisCommand(RedisConstants.UninitializedDbIndex, RedisCommandList.Sentinel, RedisCommandList.SentinelIsMasterDownByAddr,
                                                     ipAddress.ToBytes(), port.ToBytes(),
                                                     ((long)RedisCommon.EpochNow()).ToBytes(), runId.ToBytes()));

            if (!ReferenceEquals(array, null))
            {
                var info = RedisIsMasterDownInfo.Parse(array);
                return(new RedisResult <RedisIsMasterDownInfo>(info));
            }
            return(new RedisResult <RedisIsMasterDownInfo>(RedisIsMasterDownInfo.Empty));
        }
Example #11
0
 public DowloadController(CnblogDAL cnblogDal, RedisCommon redisCommon, IHostingEnvironment hostingEnvironment) : base(cnblogDal, redisCommon)
 {
     _hostingEnvironment = hostingEnvironment;
 }
Example #12
0
 public string GetField(TModel model)
 {
     return(RedisCommon.GetPrimaryKeysValuesStr <TModel>(model, primaryKeysProperties));
 }
Example #13
0
        /// <summary>
        ///     在调用操作方法之前发生。
        /// </summary>
        /// <param name="actionContext">操作上下文。</param>
        public override async System.Threading.Tasks.Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 判断是否忽略验证
            if (context.ActionDescriptor is ControllerActionDescriptor cad)
            {
                var controleIgnor = cad.ControllerTypeInfo.GetCustomAttributes(inherit: true).Any(x => x is IgnorValidateSignatureAttribute || x is InnerServiceAttribute || x is AllowAnonymousAttribute);
                if (controleIgnor)
                {
                    return;
                }
                var actionIgnor = cad.MethodInfo.GetCustomAttributes(inherit: true).Any(x => x is IgnorValidateSignatureAttribute || x is InnerServiceAttribute || x is AllowAnonymousAttribute);
                if (actionIgnor)
                {
                    return;
                }
            }
            ApiResultModel <string> apiResult = null;
            HttpRequest             request   = context.HttpContext.Request;

            #region 票据

            string ticket = "";
            var    secret = "";
            if (context.RouteData.Values["Action"].ToString().ToLower() != "getappticket")
            {
                if (request.Headers.ContainsKey(TicketKey))
                {
                    ticket = request.Headers[TicketKey].ToString();
                    var redisKey  = RedisCommon.GetTicketKey(ticket);
                    var redisData = RedisClient.Get <AppTicketModel>(RedisDatabase.DB_AuthorityService, redisKey);
                    if (redisData == null)
                    {
                        apiResult = new ApiResultModel <string>()
                        {
                            Code = ApiResultCode.TicketInvalid
                        };
                        context.Result = new JsonResult(apiResult);
                        return;
                    }
                    secret = redisData.AppSecret;
                }
                else
                {
                    apiResult = new ApiResultModel <string>()
                    {
                        Code = ApiResultCode.NoTicket
                    };
                    context.Result = new JsonResult(apiResult);
                    return;
                }
            }
            else
            {
                secret = AppSettingsHelper.Configuration["ApiConfig:SignDefaultKey"];//生成票据时,签名用默认key
            }

            #endregion

            #region  签名

            Dictionary <string, object> dictionary = null;

            if (request.Method == "POST")
            {
                if (request.ContentLength > 0)
                {
                    request.Body.Position = 0;
                    Stream stream = request.Body;
                    byte[] buffer = new byte[request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);

                    var bodyStr = Encoding.UTF8.GetString(buffer);
                    dictionary = JsonHelper.DeserializeObject <Dictionary <string, object> >(bodyStr);
                }
            }
            else
            {
                dictionary = new Dictionary <string, object>(context.ActionArguments);
            }

            if (!dictionary.ContainsKey(SignKey))//参数不包含签名
            {
                apiResult = new ApiResultModel <string>()
                {
                    Code = ApiResultCode.NoSign
                };
                context.Result = new JsonResult(apiResult);
                return;
            }
            else if (!dictionary.ContainsKey(TimestampKey))//参数不包含时间戳
            {
                apiResult = new ApiResultModel <string>()
                {
                    Code = ApiResultCode.NoTimestamp
                };
                context.Result = new JsonResult(apiResult);
                return;
            }

            var keys = dictionary.Keys.ToList();
            foreach (var key in keys)
            {
                //参数为集合类型
                var value = dictionary[key];
                if (value != null && value.GetType().Namespace == "Newtonsoft.Json.Linq")
                {
                    dictionary[key] = JsonHelper.SerializeObject(value);
                }
            }

            //验证签名
            apiResult = ValidateSignature(dictionary, secret);
            if (apiResult.Code != ApiResultCode.Success)
            {
                context.Result = new JsonResult(apiResult);
                return;
            }

            #endregion

            await base.OnActionExecutionAsync(context, next);
        }
Example #14
0
        public string GetKey(string field, string value)
        {
            string keyValueStr = RedisCommon.GetKeyValueStr(field, value);

            return(GetKey(keyValueStr));
        }
Example #15
0
        /// <summary>
        /// 生成票据
        /// </summary>
        /// <param name="requestModel"></param>
        /// <returns></returns>
        public ApiResultModel <AddAppTicketResponseModel> GetAppTicket(AddAppTicketRequestModel requestModel)
        {
            var result = new ApiResultModel <AddAppTicketResponseModel>()
            {
                Message = "生成票据失败"
            };

            if (requestModel.AppId.IsNullOrEmpty())
            {
                result.Message = "AppId不能为空";
                return(result);
            }
            if (requestModel.DeviceNo.IsNullOrEmpty())
            {
                result.Message = "客户端设备号不能为空";
                return(result);
            }
            var clentType  = requestModel.ClientType.GetEnumDescription();
            var nonce      = Utils.GetNonce();
            var ticket     = AuthenticationHelper.GetTicket(requestModel.AppId, clentType, requestModel.DeviceNo, nonce);
            var secret     = AuthenticationHelper.GetAppSecret(requestModel.AppId, clentType, requestModel.DeviceNo, nonce);
            var resultData = new AddAppTicketResponseModel()
            {
                Ticket    = ticket,
                AppSecret = secret
            };
            AppTicket model = _db.AppTicket.FirstOrDefault(x => x.AppId == requestModel.AppId && x.ClientType == clentType && x.DeviceNo == requestModel.DeviceNo);

            if (model == null)
            {
                model = new AppTicket()
                {
                    Id             = GuidTool.GetGuid(),
                    AppId          = requestModel.AppId,
                    ClientType     = clentType,
                    DeviceNo       = requestModel.DeviceNo,
                    Noncestr       = nonce,
                    AppSecret      = secret,
                    Ticket         = ticket,
                    LastUpdateTime = DateTime.Now
                };
                _db.AppTicket.Add(model);
                _db.Entry(model).State = EntityState.Added;
                _db.SaveChanges();
            }
            else
            {
                model.Noncestr       = nonce;
                model.AppSecret      = secret;
                model.Ticket         = ticket;
                model.LastUpdateTime = DateTime.Now;

                _db.AppTicket.Attach(model);
                _db.Entry(model).Property(x => x.Noncestr).IsModified       = true;
                _db.Entry(model).Property(x => x.AppSecret).IsModified      = true;
                _db.Entry(model).Property(x => x.Ticket).IsModified         = true;
                _db.Entry(model).Property(x => x.LastUpdateTime).IsModified = true;
                _db.SaveChanges();
            }

            //缓存
            var redisKey  = RedisCommon.GetTicketKey(ticket);
            var redisData = model.MapTo <AppTicketModel>();

            RedisClient.Set(RedisDatabase.DB_AuthorityService, redisKey, redisData, 60);//1小时

            result.Data = resultData;
            result.Code = ApiResultCode.Success;
            return(result);
        }
Example #16
0
 public BaseController(CnblogDAL cnblogDal, RedisCommon redisCommon)
 {
     this.CnblogDal   = cnblogDal;
     this.RedisCommon = redisCommon;
 }
        public void TryParse(RedisBufferContext context)
        {
            var buffer = context.Buffer;

            if (buffer != null)
            {
                var bufferLen = buffer.Length;

                var contextLen    = context.Length;
                var contextOffset = context.Offset;

                if (bufferLen == 0 || contextLen <= 0 ||
                    contextOffset < 0 || contextOffset >= bufferLen)
                {
                    return;
                }

                context.Length = Math.Min(contextLen, bufferLen - contextOffset);

                var sign = buffer[contextOffset];
                switch (sign)
                {
                case BulkStringSign:
                {
                    context.Offset++;
                    context.Length--;

                    context.ResultType = RedisRawObjectType.BulkString;

                    byte[] bytes;
                    if (!TryParseLine(context, out bytes))
                    {
                        context.Offset--;
                        context.Length++;
                    }
                    else
                    {
                        long dataSize;
                        if (!bytes.TryParse(out dataSize))
                        {
                            throw new RedisException("Invalid bulk string size", RedisErrorCode.CorruptResponse);
                        }

                        if (dataSize > RedisConstants.MinusOne)
                        {
                            var iSize = checked ((int)dataSize);

                            if (context.Length >= iSize + CRLFLength)
                            {
                                var crPos = context.Offset + iSize;
                                if (!(buffer[crPos] == CR && buffer[crPos + 1] == LF))
                                {
                                    throw new RedisException("Invalid bulk string data termination", RedisErrorCode.CorruptResponse);
                                }

                                context.Completed = true;
                                if (iSize == 0)
                                {
                                    context.Result = new RedisBytes(new byte[0]);
                                }
                                else
                                {
                                    var result = new byte[iSize];
                                    Array.Copy(buffer, context.Offset, result, 0, iSize);

                                    context.Result = new RedisBytes(result);
                                }

                                context.Offset += iSize + CRLFLength;
                                context.Length -= iSize + CRLFLength;
                            }
                        }
                        else
                        {
                            if (dataSize < RedisConstants.MinusOne)
                            {
                                throw new RedisException("Invalid bulk string size", RedisErrorCode.CorruptResponse);
                            }

                            context.Completed = true;
                            context.Result    = new RedisBytes(null);
                        }
                    }
                }
                break;

                case ArraySign:
                {
                    context.Offset++;
                    context.Length--;

                    context.ResultType = RedisRawObjectType.Array;

                    byte[] bytes;
                    if (!TryParseLine(context, out bytes))
                    {
                        context.Offset--;
                        context.Length++;
                    }
                    else
                    {
                        long itemCount;
                        if (!bytes.TryParse(out itemCount))
                        {
                            throw new RedisException("Invalid bulk string size", RedisErrorCode.CorruptResponse);
                        }

                        if (itemCount > RedisConstants.Zero)
                        {
                            var iCount = checked ((int)itemCount);

                            var array = new RedisArray(iCount);
                            var items = array.RawData as IList <RedisResult>;

                            for (var i = 0; i < iCount; i++)
                            {
                                var innerContext =
                                    new RedisBufferContext
                                {
                                    Buffer = buffer,
                                    Length = context.Length,
                                    Offset = context.Offset,
                                };

                                TryParse(innerContext);
                                if (!innerContext.Completed)
                                {
                                    return;
                                }

                                context.Offset = innerContext.Offset;
                                context.Length = innerContext.Length;

                                items.Add(innerContext.Result);
                            }

                            array.TrySetCompleted();

                            context.Result    = array;
                            context.Completed = true;
                        }
                        else if (itemCount == RedisConstants.Zero)
                        {
                            context.Result    = new RedisArray(new List <RedisResult>(), 0);
                            context.Completed = true;
                        }
                        else
                        {
                            context.Result    = new RedisArray(null, -1);
                            context.Completed = true;
                        }
                    }
                }
                break;

                case SimpleStringSign:
                {
                    context.Offset++;
                    context.Length--;

                    context.ResultType = RedisRawObjectType.SimpleString;

                    byte[] bytes;
                    if (!TryParseLine(context, out bytes))
                    {
                        context.Offset--;
                        context.Length++;
                    }
                    else
                    {
                        context.Result    = new RedisString((bytes == null) ? null : RedisCommon.ToUTF8String(bytes));
                        context.Completed = true;
                    }
                }
                break;

                case ErrorSign:
                {
                    context.Offset++;
                    context.Length--;

                    context.ResultType = RedisRawObjectType.Error;

                    byte[] bytes;
                    if (!TryParseLine(context, out bytes))
                    {
                        context.Offset--;
                        context.Length++;
                    }
                    else
                    {
                        context.Result    = new RedisError((bytes == null) ? null : RedisCommon.ToUTF8String(bytes));
                        context.Completed = true;
                    }
                }
                break;

                case NumberSign:
                {
                    context.Offset++;
                    context.Length--;

                    context.ResultType = RedisRawObjectType.Integer;

                    byte[] bytes;
                    if (!TryParseLine(context, out bytes))
                    {
                        context.Offset--;
                        context.Length++;
                    }
                    else
                    {
                        long number;
                        if (!bytes.TryParse(out number))
                        {
                            throw new RedisException("Invalid integer value", RedisErrorCode.CorruptResponse);
                        }

                        context.Result    = new RedisInteger(number);
                        context.Completed = true;
                    }
                }
                break;

                default:
                    throw new RedisException("Undefined redis response type", RedisErrorCode.CorruptResponse);
                }
            }
        }
Example #18
0
 public BlogController(CnblogDAL cnblogDal, RedisCommon redisCommon) : base(cnblogDal, redisCommon)
 {
 }