Example #1
0
        /// <summary>
        /// 获取产品标签(加缓存)
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List <EntSpecification> GetListByCach(int appId, int fid, int pageSize, int pageIndex, ref int count)
        {
            string strwhere    = $"aid={appId} and state=1 and parentid={fid}";
            string key         = string.Format(Redis_EntSpecificationList, appId, pageSize, pageIndex);
            string version_key = string.Format(Redis_EntSpecificationList_version, appId);
            int    entEntSpecification_version = RedisUtil.GetVersion(version_key);

            RedisModel <EntSpecification> list = RedisUtil.Get <RedisModel <EntSpecification> >(key);

            if (list == null || list.DataList == null || list.DataList.Count <= 0 || list.Count <= 0 || entEntSpecification_version != list.DataVersion)
            {
                list             = new RedisModel <EntSpecification>();
                list.DataList    = GetList(strwhere, pageSize, pageIndex, "*", " sort desc,id asc ");
                count            = GetCount(strwhere);
                list.Count       = count;
                list.DataVersion = entEntSpecification_version;

                RedisUtil.Set <RedisModel <EntSpecification> >(key, list, TimeSpan.FromHours(12));
            }
            else
            {
                count = list.Count;
            }

            return(list.DataList);
        }
Example #2
0
        /// <summary>
        /// 获取当前队列信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public override SortQueue GetModel(int Id)
        {
            string model_key   = string.Format(Redis_SortQueue, Id);
            string version_key = string.Format(Redis_SortQueue_version, Id);

            RedisModel <SortQueue> redisModel_Store = RedisUtil.Get <RedisModel <SortQueue> >(model_key);
            int version = RedisUtil.GetVersion(version_key);

            if (redisModel_Store == null || redisModel_Store.DataList == null ||
                redisModel_Store.DataList.Count > 0 || redisModel_Store.DataVersion != version)
            {
                redisModel_Store = new RedisModel <SortQueue>();
                List <SortQueue> store = new List <SortQueue>()
                {
                    base.GetModel(Id)
                };

                redisModel_Store.DataList    = store;
                redisModel_Store.DataVersion = version;
                redisModel_Store.Count       = store.Count;

                RedisUtil.Set <RedisModel <SortQueue> >(model_key, redisModel_Store, TimeSpan.FromHours(12));
            }
            return(redisModel_Store.DataList[0]);
        }
Example #3
0
        public void Run(IConnection nats, ConnectionMultiplexer redis)
        {
            var events = nats.Observe("events")
                         .Where(m => m.Data?.Any() == true)
                         .Select(m => Encoding.Default.GetString(m.Data));

            events.Subscribe(msg =>
            {
                IDatabase db = redis.GetDatabase();
                string id    = msg.Split('|').Last();
                string JSON  = db.StringGet(id);

                RedisModel model = JsonSerializer.Deserialize <RedisModel>(JSON);

                string str = model.Data;

                double vowels     = Regex.Matches(model.Data, @"[AEIOUaeiou]").Count;
                double consonants = Regex.Matches(model.Data, @"[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm]").Count;

                double measure = vowels / Math.Max(consonants, 1);
                model.Measure  = measure;

                var result = JsonSerializer.Serialize(model);
                db.StringSet(id, result);
            });
        }
Example #4
0
        public List <AgentFollowLog> GetAgentFollowLogList(int agentdistributionrid, int pageIndex, int pageSize, ref int count, bool reflesh = false)
        {
            RedisModel <AgentFollowLog> model = new RedisModel <AgentFollowLog>();

            model = RedisUtil.Get <RedisModel <AgentFollowLog> >(string.Format(_redis_AgentFollowLogKey, agentdistributionrid, pageSize, pageIndex));
            int dataversion = RedisUtil.GetVersion(string.Format(_redis_AgentFollowLogVersion, agentdistributionrid));

            if (reflesh || model == null || model.DataList == null || model.DataList.Count <= 0 || model.DataVersion != dataversion)
            {
                model = new RedisModel <AgentFollowLog>();
                List <AgentFollowLog> list = GetListByAgentDistributionRid(agentdistributionrid, pageSize, pageIndex);

                count             = GetCountByAgentDistributionRid(agentdistributionrid);
                model.DataList    = list;
                model.DataVersion = dataversion;
                model.Count       = count;
                if (!reflesh)
                {
                    RedisUtil.Set <RedisModel <AgentFollowLog> >(string.Format(_redis_AgentFollowLogKey, agentdistributionrid, pageSize, pageIndex), model);
                }
            }
            else
            {
                count = model.Count;
            }

            return(model.DataList);
        }
Example #5
0
        /// <summary>
        /// 获取当前 正在排队的 队列数据集合
        /// </summary>
        /// <param name="aId"></param>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public List <SortQueue> GetListByQueueing(int aId, int storeId = 0)
        {
            string model_key   = string.Format(Redis_SortQueues_queueing, aId, storeId);
            string version_key = string.Format(Redis_SortQueues_version, aId, storeId);

            RedisModel <SortQueue> redisModel_SortQueues = RedisUtil.Get <RedisModel <SortQueue> >(model_key);
            int version = RedisUtil.GetVersion(version_key);

            if (redisModel_SortQueues == null || redisModel_SortQueues.DataList == null ||
                redisModel_SortQueues.DataList.Count > 0 || redisModel_SortQueues.DataVersion != version)
            {
                redisModel_SortQueues = new RedisModel <SortQueue>();
                List <SortQueue> sortQueues = base.GetList($" aId={aId} {(storeId <= 0 ? "" : $" and storeId = {storeId} ")} and State = 0 ");

                string            userIds      = string.Join(",", sortQueues?.Select(s => s.userId).Distinct());
                List <C_UserInfo> userInfoList = C_UserInfoBLL.SingleModel.GetListByIds(userIds);

                sortQueues?.ForEach(s =>
                {
                    s.nickName = userInfoList?.FirstOrDefault(f => f.Id == s.userId)?.NickName;
                });
                redisModel_SortQueues.DataList    = sortQueues;
                redisModel_SortQueues.DataVersion = version;
                redisModel_SortQueues.Count       = sortQueues.Count;

                RedisUtil.Set <RedisModel <SortQueue> >(model_key, redisModel_SortQueues, TimeSpan.FromHours(12));
            }
Example #6
0
        /// <summary>
        /// 获取产品标签(加缓存)
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List <QiyeGoodsLabel> GetListByCach(int appId, int pageSize, int pageIndex, ref int count)
        {
            string strwhere    = $"aid={appId} and state=1";
            string key         = string.Format(Redis_QiyeProductLabelList, appId, pageSize, pageIndex);
            string version_key = string.Format(Redis_QiyeProductLabelList_version, appId);
            int    QiyeProductLabelList_version = RedisUtil.GetVersion(version_key);

            RedisModel <QiyeGoodsLabel> list = RedisUtil.Get <RedisModel <QiyeGoodsLabel> >(key);

            if (list == null || list.DataList == null || list.DataList.Count <= 0 || list.Count <= 0 || QiyeProductLabelList_version != list.DataVersion)
            {
                list             = new RedisModel <QiyeGoodsLabel>();
                list.DataList    = GetList(strwhere, pageSize, pageIndex, "*", " sort desc,id asc ");
                count            = GetCount(strwhere);
                list.Count       = count;
                list.DataVersion = QiyeProductLabelList_version;

                RedisUtil.Set <RedisModel <QiyeGoodsLabel> >(key, list, TimeSpan.FromHours(12));
            }
            else
            {
                count = list.Count;
            }

            return(list.DataList);
        }
Example #7
0
        public StoreGoodsSpec GetModelByCache(int id)
        {
            string model_key   = string.Format(Redis_StoreGoodsSpec, id);
            string version_key = string.Format(Redis_StoreGoodsSpec_version, id);

            int version = RedisUtil.GetVersion(version_key);
            RedisModel <StoreGoodsSpec> redisModel_StoreGoodsSpec = RedisUtil.Get <RedisModel <StoreGoodsSpec> >(model_key);

            if (redisModel_StoreGoodsSpec == null || redisModel_StoreGoodsSpec.DataList == null ||
                redisModel_StoreGoodsSpec.DataList.Count <= 0 || redisModel_StoreGoodsSpec.DataVersion != version)
            {
                redisModel_StoreGoodsSpec = new RedisModel <StoreGoodsSpec>();
                List <StoreGoodsSpec> StoreGoodsSpecs = new List <StoreGoodsSpec>()
                {
                    base.GetModel(id)
                };

                redisModel_StoreGoodsSpec.DataList    = StoreGoodsSpecs;
                redisModel_StoreGoodsSpec.DataVersion = version;
                redisModel_StoreGoodsSpec.Count       = StoreGoodsSpecs.Count;

                RedisUtil.Set <RedisModel <StoreGoodsSpec> >(model_key, redisModel_StoreGoodsSpec, TimeSpan.FromHours(12));
            }
            return(redisModel_StoreGoodsSpec.DataList[0]);
        }
Example #8
0
        public IActionResult CreateSecret(CreateSecretViewModel createSecretViewModel)
        {
            if (!this.ModelState.IsValid)
            {
                this.View("Index", createSecretViewModel);
            }

            string  key           = this.cryptoService.CreateRandomString(24);
            string  encryptedData = this.cryptoService.EncryptData(createSecretViewModel.Secret, createSecretViewModel.Passphrase);
            var     expiry        = TimeSpan.FromSeconds(createSecretViewModel.TTL);
            Instant expiryInstant = this.clock.GetCurrentInstant().Plus(Duration.FromTimeSpan(expiry));

            var model = new RedisModel
            {
                EncryptedData = encryptedData,
                HasPassphrase = createSecretViewModel.Passphrase != null,
            };

            string redisString = JsonConvert.SerializeObject(model);

            this.redis.StringSet(key, redisString, expiry, When.Always);

            string fullAccessUrl = this.Url.Action("ShowSecret", "Secret", new { id = key }, this.Request.Scheme, this.Request.Host.Value);
            string burnUrl       = this.Url.Action("BurnSecret", "Secret", new { id = key }, this.Request.Scheme, this.Request.Host.Value);
            var    created       = new CreatedSecretViewModel
            {
                AccessUrl          = fullAccessUrl,
                BurnUrl            = burnUrl,
                PassphraseRequired = string.IsNullOrEmpty(createSecretViewModel.Passphrase),
                Expires            = expiryInstant,
                DurationString     = this.DurationString(expiry),
            };

            return(this.View(created));
        }
Example #9
0
        /// <summary>
        /// 根据缓存读取 商品规格/规格值
        /// </summary>
        /// <param name="goodId">商品Id</param>
        /// <returns></returns>
        public StoreGoodsAttr GetModelByCache(int goodsAttrId)
        {
            string models_key  = string.Format(Redis_StoreGoodsAttr, goodsAttrId);
            string version_key = string.Format(Redis_StoreGoodsAttr_version, goodsAttrId);

            RedisModel <StoreGoodsAttr> redisModel_StoreGoodsAttr = RedisUtil.Get <RedisModel <StoreGoodsAttr> >(models_key);
            int version = RedisUtil.GetVersion(version_key);

            if (redisModel_StoreGoodsAttr == null || redisModel_StoreGoodsAttr.DataList == null ||
                redisModel_StoreGoodsAttr.DataList.Count <= 0 || redisModel_StoreGoodsAttr.DataVersion != version)
            {
                redisModel_StoreGoodsAttr = new RedisModel <StoreGoodsAttr>();
                List <StoreGoodsAttr> storeGoodsAttrSpecs = new List <StoreGoodsAttr>()
                {
                    GetModel(goodsAttrId)
                };

                redisModel_StoreGoodsAttr.DataList    = storeGoodsAttrSpecs;
                redisModel_StoreGoodsAttr.DataVersion = version;
                redisModel_StoreGoodsAttr.Count       = storeGoodsAttrSpecs.Count;

                RedisUtil.Set <RedisModel <StoreGoodsAttr> >(models_key, redisModel_StoreGoodsAttr, TimeSpan.FromHours(12));
            }
            return(redisModel_StoreGoodsAttr.DataList[0]);
        }
Example #10
0
        /// <summary>
        /// 优先从Redis或内存中读取
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="rank"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public static List <ResourceMenuInfo> getResourceMenuFormRedisOrMemory(String userName, int rank, String parentId)
        {
            //暂时先全部执行数据库
            //return getResourceMenu(userName, rank, parentId);

            RedisModel redisModel = getResourceMenuOnlyFormRedisOrMemory(userName);
            //Log4netHelper.WriteErrorLogByLog4Net(typeof(JwtHelp), "查询内存数据:" + JsonConvert.SerializeObject(redisModel));
            List <ResourceMenuInfo> menus = new List <ResourceMenuInfo>();

            if (redisModel == null)
            {//说明redis或内存中没有
                menus = getResourceMenu(userName, rank, parentId);
                setResourceMenuToRedisOrMemory(userName, menus);
                redisModel = new RedisModel()
                {
                    resourceMenuInfoList = menus,
                    updateTime           = WIPCommon.ForamtCurDateTime(),
                    userName             = userName
                };
                //Log4netHelper.WriteInfoLogByLog4Net(typeof(JwtHelp), "redisModel:" + JsonConvert.SerializeObject(redisModel));
            }

            if (redisModel == null)
            {
                return(null);
            }
            return(redisModel.resourceMenuInfoList);

            //*/
        }
Example #11
0
        public StoreGoods GetModelByCache(int id)
        {
            string model_key   = string.Format(Redis_StoreGoods, id);
            string version_key = string.Format(Redis_StoreGoods_version, id);

            int version = RedisUtil.GetVersion(version_key);
            RedisModel <StoreGoods> redisModel_StoreGood = RedisUtil.Get <RedisModel <StoreGoods> >(model_key);

            //if (redisModel_StoreGood == null || redisModel_StoreGood.DataList == null
            //        || redisModel_StoreGood.DataList.Count <= 0 || redisModel_StoreGood.DataVersion != version)
            //{
            redisModel_StoreGood = new RedisModel <StoreGoods>();
            List <StoreGoods> StoreGoods = new List <StoreGoods>()
            {
                GetModel(id)
            };

            redisModel_StoreGood.DataList    = StoreGoods;
            redisModel_StoreGood.DataVersion = version;
            redisModel_StoreGood.Count       = StoreGoods.Count;

            RedisUtil.Set <RedisModel <StoreGoods> >(model_key, redisModel_StoreGood, TimeSpan.FromHours(12));
            //}
            return(redisModel_StoreGood.DataList[0]);
        }
Example #12
0
        public List <SystemUpdateMessage> GetListByPage(int pageSize, int pageIndex, ref int count)
        {
            RedisModel <SystemUpdateMessage> model = new RedisModel <SystemUpdateMessage>();

            model = RedisUtil.Get <RedisModel <SystemUpdateMessage> >(string.Format(_redis_allsystempupdatelogkey, pageSize, pageIndex));
            int dataversion = RedisUtil.GetVersion(_redis_systempupdatelogversion);

            if (model == null || model.DataList == null || model.DataList.Count <= 0 || model.DataVersion != dataversion)
            {
                model = new RedisModel <SystemUpdateMessage>();
                string sqlwhere = $"Type in (0,1) and state>-1";
                model.DataList = base.GetList(sqlwhere, pageSize, pageIndex, "*", "AddTime desc");

                count = base.GetCount(sqlwhere);

                model.DataVersion = dataversion;
                model.Count       = count;
                RedisUtil.Set <RedisModel <SystemUpdateMessage> >(string.Format(_redis_allsystempupdatelogkey, pageSize, pageIndex), model);
            }
            else
            {
                count = model != null?model.Count:0;
            }

            return(model.DataList);
        }
Example #13
0
        public void AddToDb(long count)
        {
            //var aes = new AesManaged();

            for (long i = 0; i < count; i++)
            {
                //aes.GenerateKey();

                //var model = new RedisModel()
                //{
                //    Key = Encoding.UTF8.GetString(aes.Key, 0, aes.Key.Length),
                //    Value = Encoding.UTF8.GetString(aes.Key, 0, aes.Key.Length),
                //    ExpireDateTime = DateTime.Now.AddMinutes(1)
                //};

                var model = new RedisModel()
                {
                    Key            = i.ToString(),
                    Value          = i,
                    ExpireDateTime = DateTime.Now.AddMinutes(1)
                };

                _redisService.Set(model);
                _consoleInfo.SentObjectIncreasment();
                _consoleInfo.DbObjectCounter(_redisService.TotalCount());
            }
        }
Example #14
0
        public List <AgentQrCode> GetAgentQrCodeList(int agentid, int pageIndex, int pageSize, ref int count, bool reflesh = false)
        {
            RedisModel <AgentQrCode> model = new RedisModel <AgentQrCode>();

            model = RedisUtil.Get <RedisModel <AgentQrCode> >(string.Format(_redis_AgentQrCodeKey, agentid, pageSize, pageIndex));
            int dataversion = RedisUtil.GetVersion(string.Format(_redis_AgentQrCodeVersion, agentid));

            if (reflesh || model == null || model.DataList == null || model.DataList.Count <= 0 || model.DataVersion != dataversion)
            {
                model = new RedisModel <AgentQrCode>();
                List <AgentQrCode> list = GetDataList(agentid, pageSize, pageIndex);

                if (list == null || list.Count <= 0)
                {
                    return(new List <AgentQrCode>());
                }

                string qrcodeids = string.Join(",", list.Select(s => s.Id).Distinct());
                List <AgentCustomerRelation> rlist = AgentCustomerRelationBLL.SingleModel.GetListByQrCodeId(qrcodeids);
                if (rlist != null && rlist.Count > 0)
                {
                    string         userids     = "'" + string.Join("','", rlist.Select(s => s.useraccountid)) + "'";
                    List <Account> accountlist = AccountBLL.SingleModel.GetListByAccountids(userids);
                    if (accountlist != null && accountlist.Count > 0)
                    {
                        foreach (AgentQrCode item in list)
                        {
                            AgentCustomerRelation rmodel = rlist.FirstOrDefault(f => f.QrcodeId == item.Id);
                            if (rmodel == null)
                            {
                                continue;
                            }
                            Account account = accountlist.Where(w => w.Id.ToString() == rmodel.useraccountid).FirstOrDefault();
                            if (account == null)
                            {
                                continue;
                            }
                            item.LoginId            = account.LoginId;
                            item.OpenExtension      = rmodel.OpenExtension;
                            item.CustomerRelationId = rmodel.id;
                        }
                    }
                }

                count             = GetCountByAgentId(agentid);
                model.DataList    = list;
                model.DataVersion = dataversion;
                model.Count       = count;
                RedisUtil.Set <RedisModel <AgentQrCode> >(string.Format(_redis_AgentQrCodeKey, agentid, pageSize, pageIndex), model);
            }
            else
            {
                count = model.Count;
            }

            return(model.DataList);
        }
Example #15
0
        public void OnGet()
        {
            var info  = _redisAccess.GetInfo(out var error);
            var input = RedisManager.GetRedisModel(info);

            input.Servers = _options.Servers;
            input.Message = error;
            Input         = input;
        }
Example #16
0
        /// <summary>
        /// 获取用户更新日志
        /// </summary>
        /// <returns></returns>
        public List <SystemUpdateMessage> GetSystemUpdateMessageList(string accountid, string accountaddtime)
        {
            RedisModel <SystemUpdateMessage> model = new RedisModel <SystemUpdateMessage>();

            model = RedisUtil.Get <RedisModel <SystemUpdateMessage> >(string.Format(_redis_systempupdatelogkey, accountid));
            int dataversion = RedisUtil.GetVersion(_redis_systempupdatelogversion);

            if (model == null || model.DataList == null || model.DataList.Count <= 0 || model.DataVersion != dataversion)
            {
                int agentid = 0;
                //判断是否是代理商
                Agentinfo agentinfo = AgentinfoBLL.SingleModel.GetModelByAccoundId(accountid);
                if (agentinfo != null)
                {
                    agentid = agentinfo.id;
                }

                model = new RedisModel <SystemUpdateMessage>();
                List <SystemUpdateMessage> list = new List <SystemUpdateMessage>();
                //系统更新日志数量
                int smessagecount = GetSystemMessageCount(0);
                //用户查看日志数量
                int smessageuserlogcount = SystemUpdateUserLogBLL.SingleModel.GetSMessageUserLogCount(accountid);
                //判断用户是否有未查看的更新日志
                if (!(smessagecount > 0 && smessagecount == smessageuserlogcount))
                {
                    string sqlwhere = $"state=0 and (type in (0,1) and updatetime>='{accountaddtime}' or (type=2 and accountid='{accountid}'))";
                    //如果不是代理商,查询相对应的系统更新
                    if (agentid <= 0)
                    {
                        sqlwhere = $"state=0 and ((type=0 and updatetime>='{accountaddtime}') or (type=2 and accountid='{accountid}'))";
                        //获取查询用户开通模板最小时间查询语句,
                        string tids = XcxAppAccountRelationBLL.SingleModel.GetListXcxappListSQL(accountid);
                        if (!string.IsNullOrEmpty(tids))
                        {
                            sqlwhere = $"state=0 and ((type=0 and updatetime>='{accountaddtime}') or (type=2 and accountid='{accountid}') {tids})";
                        }
                    }
                    List <SystemUpdateUserLog> logs = SystemUpdateUserLogBLL.SingleModel.GetList($"state = 1 and accountid = '{accountid}'");
                    if (logs != null && logs.Count > 0)
                    {
                        sqlwhere += string.Format(" and id not in({0})", string.Join(",", logs.Select(s => s.UpdateMessageId).Distinct()));
                    }


                    //获取还未查看的系统更新日志
                    list = GetList(sqlwhere, 10000, 1, "", "updatetime desc");
                }

                model.DataList    = list;
                model.DataVersion = dataversion;
                RedisUtil.Set <RedisModel <SystemUpdateMessage> >(string.Format(_redis_systempupdatelogkey, accountid), model);
            }

            return(model.DataList);
        }
Example #17
0
        /// <summary>
        /// 获取用户所有更新日志
        /// </summary>
        /// <returns></returns>
        public List <SystemUpdateMessage> GetAllSystemUpdateMessageList(string tids, string accountid, int agentid, int pageIndex, int pageSize, ref int count)
        {
            RedisModel <SystemUpdateMessage> model = new RedisModel <SystemUpdateMessage>();

            model = RedisUtil.Get <RedisModel <SystemUpdateMessage> >(string.Format(_redis_userallsystempupdatelogkey, accountid, pageSize, pageIndex));
            int dataversion = RedisUtil.GetVersion(_redis_systempupdatelogversion);

            if (model == null || model.DataList == null || model.DataList.Count <= 0 || model.DataVersion != dataversion)
            {
                string sql = $"select sys.*,(select state from systemupdateuserlog sysl where sys.id = sysl.updatemessageid and sysl.AccountId='{accountid}') isread from systemupdatemessage sys where ";
                model = new RedisModel <SystemUpdateMessage>();
                List <SystemUpdateMessage> list = new List <SystemUpdateMessage>();
                string sqlwhere = $"state=0 and (type in (0,1) or (type=2 and accountid='{accountid}'))";
                //如果不是代理商,查询相对应的系统更新
                if (agentid <= 0)
                {
                    sqlwhere = $"state=0 and (type=0 or (type=2 and accountid='{accountid}'))";
                    if (!string.IsNullOrEmpty(tids))
                    {
                        sqlwhere = $"state=0 and (type=0 or (type=2 and accountid='{accountid}') or  (tid in ({tids}) and type=1))";
                    }
                }

                sql += sqlwhere;
                sql += $" ORDER BY isread asc,updatetime DESC LIMIT {(pageIndex - 1) * pageSize},{pageSize}";

                using (MySqlDataReader dr = SqlMySql.ExecuteDataReaderMaster(connName, CommandType.Text, sql, null))
                {
                    while (dr.Read())
                    {
                        SystemUpdateMessage sysmodel = GetModel(dr);
                        if (dr["isread"] != DBNull.Value)
                        {
                            sysmodel.IsRead = Convert.ToInt32(dr["isread"]);
                        }

                        list.Add(sysmodel);
                    }
                }

                count = GetCount(sqlwhere);

                model.DataList    = list;
                model.DataVersion = dataversion;
                model.Count       = count;
                RedisUtil.Set <RedisModel <SystemUpdateMessage> >(string.Format(_redis_userallsystempupdatelogkey, accountid, pageSize, pageIndex), model);
            }
            else
            {
                count = model.Count;
            }

            return(model.DataList);
        }
Example #18
0
        public List <CustomModelRelation> GetCustomModelRelationList(int aid, int pageSize, int pageIndex, ref int count, bool reflesh = true)
        {
            RedisModel <CustomModelRelation> model = RedisUtil.Get <RedisModel <CustomModelRelation> >(string.Format(_redis_CustomModelRelationKey, aid, pageSize, pageIndex));
            int dataversion = RedisUtil.GetVersion(string.Format(_redis_CustomModelRelationVersion));

            if (reflesh || model == null || model.DataList == null || model.DataList.Count <= 0 || model.DataVersion != dataversion)
            {
                model = new RedisModel <CustomModelRelation>();
                List <CustomModelRelation> list = new List <CustomModelRelation>();
                string sql        = $@"select cm.*,xr.versionid,cur.custommodelid from custommodelrelation cm
                            left join xcxappaccountrelation xr on cm.aid = xr.id
                            left join (select * from custommodeluserrelation where aid={aid}) cur on cur.custommodelid = cm.id ";
                string sqlcount   = $@"select Count(*) from custommodelrelation cm";
                string sqlwhere   = $" where cm.state =1";
                string sqlorderby = $" order by cur.custommodelid desc,cm.updatetime desc LIMIT {(pageIndex - 1) * pageSize},{pageSize} ";
                using (MySqlDataReader dr = SqlMySql.ExecuteDataReaderMaster(connName, CommandType.Text, sql + sqlwhere + sqlorderby, null))
                {
                    while (dr.Read())
                    {
                        CustomModelRelation amodel = base.GetModel(dr);
                        if (dr["custommodelid"] != DBNull.Value)
                        {
                            amodel.CustommodelId = Convert.ToInt32(dr["custommodelid"]);
                        }
                        if (dr["versionid"] != DBNull.Value)
                        {
                            amodel.VersionId = Convert.ToInt32(dr["versionid"]);
                        }
                        list.Add(amodel);
                    }
                }
                if (list == null && list.Count <= 0)
                {
                    return(new List <CustomModelRelation>());
                }

                count             = base.GetCountBySql(sqlcount + sqlwhere);
                model.DataList    = list;
                model.DataVersion = dataversion;
                model.Count       = count;
                if (!reflesh)
                {
                    RedisUtil.Set <RedisModel <CustomModelRelation> >(string.Format(_redis_CustomModelRelationKey, aid, pageSize, pageIndex), model);
                }
            }
            else
            {
                count = model.Count;
            }
            return(model.DataList);
        }
Example #19
0
        public IActionResult Index(RedisModel model)
        {
            if (model.HostName?.EndsWith(".redis.cache.windows.net") ?? false)
            {
                model.HostName = StrUtil.LeftBefore(model.HostName, "\\.");
            }
            var cu = ControllerUtils.From(this);
            cu.PersistInput("HostName", model, RedisModel.Default.HostName);
            cu.PersistInput("AccessKey", model, RedisModel.Default.AccessKey);
            cu.PersistInput("Key", model, RedisModel.Default.Key);

            try
            {
                switch (model.Mode)
                {
                    case RedisModel.Modes.Ping:
                        var ret = GetRedis(model).Ping();
                        model.Result = $"PONG {ret.TotalMilliseconds}[ms]";
                        break;
                    case RedisModel.Modes.Get:
                        var rv = GetRedis(model).StringGet(new RedisKey(model.Key));
                        if (rv.HasValue)
                        {
                            model.Result = rv.ToString();
                        }
                        else
                        {
                            model.ErrorMessage = $"Key '{model.Key}' has not a value";
                        }
                        break;
                    case RedisModel.Modes.Set:
                        var sr = GetRedis(model).StringSet(new RedisKey(model.Key), new RedisValue(model.Value));
                        if (sr)
                        {
                            model.Result = $"OK : Set '{model.Key}' = '{model.Value}'";
                        }
                        else
                        {
                            model.ErrorMessage = $"Error : Set '{model.Key}' = '{model.Value}'";
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                model.ErrorMessage = ex.Message;
            }
            return View(model);
        }
Example #20
0
        public IActionResult ShowSecret(string id)
        {
            var vm = new ShowSecretViewModel();

            string data = this.redis.StringGet(id);

            if (data != null)
            {
                RedisModel model = JsonConvert.DeserializeObject <RedisModel>(data);
                vm.HasPassphrase = model.HasPassphrase;
            }

            return(this.View(vm));
        }
Example #21
0
 public void Expires()
 {
     const string key = "key";
     var target = new RedisModel();
     target.Set(key, "value");
     var expires = DateTime.Now;
     target.Expire(key, expires);
     Thread.Sleep(TimeSpan.FromMilliseconds(1));
     var keys = target.GetExpiredKeys();
     Assert.IsTrue(keys.Single() == key);
     var expected = target.Expires(key);
     Assert.IsTrue(expected.HasValue);
     Assert.AreEqual(expected.Value, expires);
 }
Example #22
0
        public List <KeyWordType> GetListByParentId(int parentId, int state)
        {
            RedisModel <KeyWordType> model = RedisUtil.Get <RedisModel <KeyWordType> >(_redis_KeyWordTypeListKey);
            int dataversion = RedisUtil.GetVersion(_redis_KeyWordTypeListVersion);

            if (model == null || model.DataList == null || model.DataList.Count <= 0 || model.DataVersion != dataversion)
            {
                model = new RedisModel <KeyWordType>();
                string sqlWhere = $"parentid={parentId} and state>={0}";
                model.DataList = base.GetList(sqlWhere);
                RedisUtil.Set <RedisModel <KeyWordType> >(_redis_KeyWordTypeListKey, model);
            }

            return(model.DataList);
        }
Example #23
0
        public async Task SetAsync(RedisModel model)
        {
            var dbValue = model.Value is string?model.Value.ToString() : JsonConvert.SerializeObject(model.Value);

            var dbObject = new KeyValuePair <RedisKey, RedisValue>[1]
            {
                new KeyValuePair <RedisKey, RedisValue>(model.Key, dbValue)
            };

            await _redisDatabase.StringSetAsync(dbObject, When.NotExists);

            if (model.ExpireDateTime.HasValue)
            {
                _redisDatabase.KeyExpire(model.Key, model.ExpireDateTime.GetValueOrDefault(DateTime.Now).AddMinutes(1));
            }
        }
Example #24
0
        public void Expires()
        {
            const string key    = "key";
            var          target = new RedisModel();

            target.Set(key, "value");
            var expires = DateTime.Now;

            target.Expire(key, expires);
            Thread.Sleep(TimeSpan.FromMilliseconds(1));
            var keys = target.GetExpiredKeys();

            Assert.IsTrue(keys.Single() == key);
            var expected = target.Expires(key);

            Assert.IsTrue(expected.HasValue);
            Assert.AreEqual(expected.Value, expires);
        }
Example #25
0
        public IActionResult ShowSecretConfirmed(string id)
        {
            string data = this.redis.StringGet(id);

            if (data == null)
            {
                return(this.View(new ShowSecretViewModel
                {
                    DoesntExist = true,
                }));
            }

            RedisModel model = JsonConvert.DeserializeObject <RedisModel>(data);
            var        vm    = new ShowSecretViewModel
            {
                HasPassphrase = model.HasPassphrase,
            };

            try
            {
                Microsoft.Extensions.Primitives.StringValues passphrase = this.Request.Form["passphrase"];

                string secret = this.cryptoService.DecryptData(model.EncryptedData, passphrase);

                // always delete before showing to prevent it from being seen twice
                this.redis.KeyDelete(id);

                vm.Secret = secret;
                return(this.View(vm));
            }
            catch (Exception)
            {
                if (model.HasPassphrase)
                {
                    vm.DidError = true;
                    return(this.View("ShowSecret", vm));
                }
                else
                {
                    throw;
                }
            }
        }
Example #26
0
        /// <summary>
        /// 从Redis或缓存中获取权限
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="rank"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private static RedisModel getResourceMenuOnlyFormRedisOrMemory(String userName)
        {
            RedisModel redisModel = null;

            if (AuthType == WipAuthType.REDIS)
            {
            }
            else
            {
                if (wipAuthCacheDict.ContainsKey(userName))
                {
                    redisModel = wipAuthCacheDict[userName];
                }
            }

            return(redisModel);

            //*/
        }
Example #27
0
        /// <summary>
        /// 权限写入Redis或内存
        /// </summary>
        /// <param name="menus"></param>
        private static void setResourceMenuToRedisOrMemory(string userName, List <ResourceMenuInfo> menus)
        {
            RedisModel redisModel = new RedisModel()
            {
                userName             = userName,
                resourceMenuInfoList = menus,
                updateTime           = WIPCommon.ForamtCurDateTime()
            };

            if (AuthType == WipAuthType.REDIS)
            {
            }
            else
            {
                //写入缓存中
                wipAuthCacheDict.TryAdd(userName, redisModel); //尝试新增
                wipAuthCacheDict[userName] = redisModel;       //更新
            }
        }
Example #28
0
        /// <summary>
        /// 更新权限到Redis
        /// </summary>
        /// <param name="userList"></param>
        public static void UpdateAuthToRedis()
        {
            try
            {
                Task.Run(() =>
                {
                    List <UserInfoLogon> userList = WIPDataAccess.CreateDAL <ICommonDAL>("CommonDAL").GetUserAccountView();

                    if (userList != null && userList.Count > 0)
                    {
                        foreach (var user in userList)
                        {
                            List <ResourceMenuInfo> menus = new List <ResourceMenuInfo>();
                            menus = getResourceMenu(user.Name, 0, "");
                            setResourceMenuToRedisOrMemory(user.Name, menus);
                        }

                        //判断如果这次内存字典中有,而userList没有的用户,表示该用户已删除了,要把他从内存中移除掉
                        List <string> removeList = new List <string>();
                        foreach (var item in wipAuthCacheDict)
                        {
                            if (!userList.Exists(t => t.Name == item.Key))
                            {
                                removeList.Add(item.Key);
                            }
                        }
                        foreach (var removeItem in removeList)
                        {
                            RedisModel redisModel = null;
                            wipAuthCacheDict.TryRemove(removeItem, out redisModel);
                        }
                    }
                    else
                    {//表示没有用户了,清空内存
                        wipAuthCacheDict = new ConcurrentDictionary <string, RedisModel>();
                    }
                });
            }
            catch
            {
                throw;
            }
        }
Example #29
0
        public void ExpiresMultiple()
        {
            var target  = new RedisModel();
            var expires = DateTime.Now;

            //add 5 keys with expiring NOW
            var range = Enumerable.Range(1, 5).Select(n => n.ToString()).ToArray();

            foreach (var key in range)
            {
                target.Set(key, key);
                target.Expire(key, expires);
            }

            //wait a bit and they should all be reported as expired
            Thread.Sleep(TimeSpan.FromMilliseconds(10));
            var expiredKeys = target.GetExpiredKeys();

            Assert.IsTrue(new HashSet <string>(expiredKeys).SetEquals(range));

            //check them individually
            foreach (var key in range)
            {
                var expected = target.Expires(key);
                Assert.IsTrue(expected.HasValue);
                Assert.AreEqual(expected.Value, expires);
            }

            //un-expire the first one and check again
            target.Persist(range[0]);
            range       = range.Skip(1).ToArray();
            expiredKeys = target.GetExpiredKeys();
            Assert.IsTrue(new HashSet <string>(expiredKeys).SetEquals(range));

            //purge and there should be no expired keys
            target.PurgeExpired();
            expiredKeys = target.GetExpiredKeys();
            Assert.AreEqual(expiredKeys.Length, 0);

            //there should now be a single key in the store
            Assert.AreEqual(target.KeyCount(), 1);
            Assert.AreEqual("1", target.Get("1"));
        }
Example #30
0
        public async Task AddToDbAsync(long count)
        {
            for (long i = 0; i < count; i++)
            {
                var aes = new AesManaged();
                aes.GenerateKey();

                var model = new RedisModel()
                {
                    Key            = aes.Key.ToString(),
                    Value          = aes.Key.ToString(),
                    ExpireDateTime = DateTime.Now.AddMinutes(1)
                };

                await _redisService.SetAsync(model);

                _consoleInfo.SentObjectIncreasment();
                _consoleInfo.DbObjectCounter(await _redisService.TotalCountAsync());
            }
        }
Example #31
0
        public RedisModel <EntStoreCode> GetListByAid(int aid, int state, int pageSize, int pageIndex)
        {
            string key                     = string.Format(_redis_EntStoreCodeList, aid, pageSize, pageIndex);
            string version_key             = string.Format(_redis_EntStoreCodeList_version, aid);
            int    version                 = RedisUtil.GetVersion(version_key);
            RedisModel <EntStoreCode> list = RedisUtil.Get <RedisModel <EntStoreCode> >(key);

            if (list == null || list.DataList == null || list.DataList.Count <= 0 || list.Count <= 0 || version != list.DataVersion)
            {
                list = new RedisModel <EntStoreCode>();
                string sqlwhere = $"aid = {aid} and state>{state}";

                #region 缓存
                list.DataList    = base.GetList(sqlwhere, pageSize, pageIndex);;
                list.Count       = base.GetCount(sqlwhere);;
                list.DataVersion = version;
                #endregion
            }
            return(list);
        }
Example #32
0
        public void ExpiresMultiple()
        {
            var target = new RedisModel();
            var expires = DateTime.Now;

            //add 5 keys with expiring NOW
            var range = Enumerable.Range(1, 5).Select(n => n.ToString()).ToArray();
            foreach (var key in range)
            {
                target.Set(key, key);
                target.Expire(key, expires);
            }

            //wait a bit and they should all be reported as expired
            Thread.Sleep(TimeSpan.FromMilliseconds(10));
            var expiredKeys = target.GetExpiredKeys();
            Assert.IsTrue(new HashSet<string>(expiredKeys).SetEquals(range));

            //check them individually
            foreach (var key in range)
            {
                var expected = target.Expires(key);
                Assert.IsTrue(expected.HasValue);
                Assert.AreEqual(expected.Value, expires);
            }

            //un-expire the first one and check again
            target.Persist(range[0]);
            range = range.Skip(1).ToArray();
            expiredKeys = target.GetExpiredKeys();
            Assert.IsTrue(new HashSet<string>(expiredKeys).SetEquals(range));

            //purge and there should be no expired keys
            target.PurgeExpired();
            expiredKeys = target.GetExpiredKeys();
            Assert.AreEqual(expiredKeys.Length, 0);

            //there should now be a single key in the store
            Assert.AreEqual(target.KeyCount(), 1);
            Assert.AreEqual("1", target.Get("1"));
        }
Example #33
0
        public void ZUnionStoreTests(Dictionary<string, double> set1, Dictionary<string,double> set2, int expectedCount, SortedSet<ZSetEntry> expectedSet, RedisModel.AggregateType aggregateType)
        {
            _target.ZAdd("s1", set1);
            _target.ZAdd("s2", set2);
            var elementCount = _target.ZUnionStore("s3", new[] { "s1", "s2" }, null, aggregateType);
            Assert.AreEqual(set1.Select(s => s.Key).Union(set2.Select(s => s.Key)).Count(), elementCount);

            Trace.WriteLine("s3 members:");
            foreach (var pair in _target.ZRangeWithScores("s3")) Trace.WriteLine(pair);

            Trace.WriteLine("s1 members:");
            foreach (var pair in _target.ZRangeWithScores("s1")) Trace.WriteLine(pair);

            Trace.WriteLine("s2 members:");
            foreach (var pair in _target.ZRangeWithScores("s2")) Trace.WriteLine(pair);
        }
Example #34
0
 public void Setup()
 {
     var config = new EngineConfiguration().ForIsolatedTest();
     _target = Db.For<RedisModel>(config);
 }