/// <summary>
        /// 根据商家id获取折扣信息和满减信息
        /// </summary>
        /// <param name="Business_Id"></param>
        /// <returns></returns>
        public ResponseModel <ActivityDTO> GetDisCountByBusinessId(int Business_Id)
        {
            var result = new ResponseModel <ActivityDTO>();

            result.error_code = Result.SUCCESS;
            string key = "GetDisCountByBusinessId" + Business_Id;

            if (Business_Id <= 0)
            {
                result.error_code = Result.ERROR;
                result.message    = "参数不合法";
                result.data       = null;
                return(result);
            }
            else if (RedisDb._redisHelper_11().KeyExists(key))
            {
                var data = RedisDb._redisHelper_11().StringGet <ActivityDTO>(key);
                result.data        = data;
                result.total_count = 1;
                return(result);
            }
            else
            {
                var businessInfo = _businessInfoService.GetById(Business_Id);
                if (businessInfo != null)
                {
                    var activityDTO = new ActivityDTO();
                    if (businessInfo.ActivityDiscount != null)
                    {
                        var activityDto = new ActivityDiscountDTO()
                        {
                            id          = businessInfo.ActivityDiscount.ActivityDiscountId,
                            discount    = businessInfo.ActivityDiscount.Discount,
                            business_id = businessInfo.BusinessInfoId
                        };
                        activityDTO.discount = activityDto;
                    }
                    var businessMinusList = businessInfo.ActivityMinusList.Where(c => c.IsDelete == (int)IsDeleteEnum.效 && c.Status == (int)EnabledEnum.效).ToList();
                    if (businessMinusList != null)
                    {
                        var minusList = new List <ActivityMinusDTO>();
                        foreach (var item in businessMinusList)
                        {
                            minusList.Add(new ActivityMinusDTO()
                            {
                                achieve_amount  = Convert.ToInt32(item.AchiveAmount),
                                activityminusid = item.ActivityMinusId,
                                business_id     = item.BusinessInfoId,
                                minus_amount    = Convert.ToInt32(item.MinusAmount)
                            });
                        }
                        activityDTO.minus = minusList;
                    }
                    result.data = activityDTO;
                    RedisDb._redisHelper_11().StringSet(key, result.data, RedisConfig._defaultExpiry);
                }
            }
            return(result);
        }
 public void Set <TKey, TValue>(RedisStoreKey <TKey> key, TValue value)
     where TValue : IRedisStorable, new()
 {
     if (DbSet(value) && IsConnected)
     {
         RedisDb.StringSet(key, value.ToRedisValue());
     }
 }
Beispiel #3
0
 /// <summary>
 /// Removes the specified fields from the hash stored at key. Non-existing fields are ignored. Non-existing keys are treated as empty hashes and this command returns 0.
 /// </summary>
 /// <param name="hashFields">The fields in the hash to delete.</param>
 /// <returns>The number of fields that were removed.</returns>
 /// <remarks>https://redis.io/commands/hdel</remarks>
 public Task <long> DeleteFieldsAsync(string[] hashFields)
 {
     if (hashFields == null)
     {
         throw new ArgumentNullException(nameof(hashFields));
     }
     return(RedisDb.HashDeleteAsync(KeyName, hashFields.Select(f => new RedisValue(f)).ToArray()));
 }
Beispiel #4
0
 /// <summary>
 /// Returns an enumerator that iterates through the collection.
 /// </summary>
 /// <returns>
 /// An enumerator that can be used to iterate through the collection.
 /// </returns>
 public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
 {
     foreach (var hashKey in RedisDb.HashKeys(RedisKey))
     {
         var redisValue = RedisDb.HashGet(RedisKey, hashKey);
         yield return(new KeyValuePair <TKey, TValue>(KeySerializer.Deserialize <TKey>(hashKey), ValueSerializer.Deserialize <TValue>(redisValue)));
     }
 }
Beispiel #5
0
 /// <summary>
 /// Returns an enumerator that iterates through the collection.
 /// </summary>
 /// <returns>
 /// An enumerator that can be used to iterate through the collection.
 /// </returns>
 public IEnumerator <T> GetEnumerator()
 {
     for (int i = 0; i < Count; i++)
     {
         var value = RedisDb.ListGetByIndex(RedisKey, i);
         yield return(value.HasValue ? Serializer.Deserialize <T>(value) : default(T));
     }
 }
Beispiel #6
0
        private void Remove <T>(T obj)
        {
            Type   t    = typeof(T);
            string guid = t.GetProperty("Identifier").GetValue(obj).ToString();

            RedisDb.SortedSetRemove(t.Name, guid);
            RedisDb.KeyDelete(guid);
        }
 private string GetCache()
 {
     if (!RedisDb.Exists(_cacheKey))
     {
         ReloadCache();
     }
     return(RedisDb.Get(_cacheKey));
 }
Beispiel #8
0
 /// <summary>
 /// When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns all the elements in the sorted set at key with a value between min and max.
 /// </summary>
 /// <param name="min">The min value to filter by.</param>
 /// <param name="max">The max value to filter by.</param>
 /// <param name="exclude">Which of <paramref name="min"/> and <paramref name="max"/> to exclude (defaults to both inclusive).</param>
 /// <param name="skip">How many items to skip.</param>
 /// <param name="take">How many items to take.</param>
 /// <remarks>https://redis.io/commands/zrangebylex</remarks>
 /// <returns>list of elements in the specified score range.</returns>
 public Task <RedisValue[]> RangeByValueAsync(
     RedisValue min,
     RedisValue max,
     Exclude exclude,
     long skip,
     long take = -1) // defaults removed to avoid ambiguity with overload with order
 {
     return(RedisDb.SortedSetRangeByValueAsync(KeyName, min, max, exclude, skip, take));
 }
Beispiel #9
0
        /// <summary>
        /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param>
        /// <param name="index">The index.</param>
        public void CopyTo(T[] array, int index)
        {
            var values = RedisDb.ListRange(RedisKey);

            for (var i = 0; i < values.Length; i++)
            {
                array[index + i] = values[i].HasValue ? Serializer.Deserialize <T>(values[i]) : default(T);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Removes the <see cref="T:System.Collections.Generic.IList`1" /> item at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index of the item to remove.</param>
        public void RemoveAt(int index)
        {
            var value = RedisDb.ListGetByIndex(RedisKey, index);

            if (!value.IsNull)
            {
                RedisDb.ListRemove(RedisKey, value);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Removes at asynchronous.
        /// </summary>
        /// <param name="tran">The tran.</param>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        public async Task RemoveAtAsync(ITransaction tran, int index)
        {
            var value = RedisDb.ListGetByIndex(RedisKey, index);

            if (!value.IsNull)
            {
                await tran.ListRemoveAsync(RedisKey, value);
            }
        }
Beispiel #12
0
 private CSRedisClientLock GetRedisLock(string cacheKey)
 {
     using (var mx = new Mutex(true, cacheKey))
     {
         mx.WaitOne();
         var getLock = RedisDb.Lock(cacheKey, 2);
         mx.Close();
         return(getLock);
     };
 }
        public async Task <bool> SetAsync <TKey, TValue>(RedisStoreKey <TKey> key, TValue value)
            where TValue : IRedisStorable, new()
        {
            if (await DbSetAsync(value))
            {
                return(!IsConnected || await RedisDb.StringSetAsync(key, value.ToRedisValue()));
            }

            return(false);
        }
Beispiel #14
0
 /// <summary>
 /// Returns the specified range of elements in the sorted set stored at key. By default the elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score.
 /// Start and stop are used to specify the min and max range for score values. Similar to other range methods the values are inclusive.
 /// </summary>
 /// <param name="start">The minimum score to filter by.</param>
 /// <param name="stop">The maximum score to filter by.</param>
 /// <param name="exclude">Which of <paramref name="start"/> and <paramref name="stop"/> to exclude (defaults to both inclusive).</param>
 /// <param name="order">The order to sort by (defaults to ascending).</param>
 /// <param name="skip">How many items to skip.</param>
 /// <param name="take">How many items to take.</param>
 /// <returns>List of elements in the specified score range.</returns>
 /// <remarks>https://redis.io/commands/zrangebyscore</remarks>
 /// <remarks>https://redis.io/commands/zrevrangebyscore</remarks>
 public Task <SortedSetEntry[]> RangeByScoreWithScoresAsync(
     double start    = double.NegativeInfinity,
     double stop     = double.PositiveInfinity,
     Exclude exclude = Exclude.None,
     Order order     = Order.Ascending,
     long skip       = 0,
     long take       = -1)
 {
     return(RedisDb.SortedSetRangeByScoreWithScoresAsync(KeyName, start, stop, exclude, order, skip, take));
 }
        static void Main(string[] args)
        {
            var db = new RedisDb("10.0.2.7,password="******"users", 1000, "hasPony", "yes");
            var v = db.ValueGet("users", 1000, "hasPony");

            db.ListSet("users", 1000, "mice", new string[] { "mouse 1", "mouse 2", "mouse 3" });
            var m = db.ListGet("users", 1000, "mice");
        }
Beispiel #16
0
 /// <summary>
 /// When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns all the elements in the sorted set at key with a value between min and max.
 /// </summary>
 /// <param name="key">The key of the sorted set.</param>
 /// <param name="min">The min value to filter by.</param>
 /// <param name="max">The max value to filter by.</param>
 /// <param name="exclude">Which of <paramref name="min"/> and <paramref name="max"/> to exclude (defaults to both inclusive).</param>
 /// <param name="order">Whether to order the data ascending or descending</param>
 /// <param name="skip">How many items to skip.</param>
 /// <param name="take">How many items to take.</param>
 /// <param name="flags">The flags to use for this operation.</param>
 /// <remarks>https://redis.io/commands/zrangebylex</remarks>
 /// <remarks>https://redis.io/commands/zrevrangebylex</remarks>
 /// <returns>list of elements in the specified score range.</returns>
 public Task <RedisValue[]> SortedSetRangeByValueAsync(
     RedisValue min  = default(RedisValue),
     RedisValue max  = default(RedisValue),
     Exclude exclude = Exclude.None,
     Order order     = Order.Ascending,
     long skip       = 0,
     long take       = -1)
 {
     return(RedisDb.SortedSetRangeByValueAsync(KeyName, min, max, exclude, order, skip, take));
 }
Beispiel #17
0
        public RRKFService()
        {
            log = LogManager.GetLogger(this.GetType());
            RedisDb.InitDb();
            this.db = RedisDb.GetRedisDb;
            rooturl = ConfigurationManager.AppSettings["rrkf_url"];
            Regex reg = new Regex("(?<domain>.*://www.+?/.*?)");

            domain = reg.Match(rooturl).Groups["domain"].Value;
            domain = domain.Remove(domain.Length - 1);
        }
Beispiel #18
0
        private void SetChace()
        {
            //全表重建缓存
            var pinple = RedisDb.StartPipe();

            foreach (var item in GetDbAll())
            {
                pinple.HSet(_cacheKey, item.Id.ToString(), item);
            }
            pinple.EndPipe();
        }
Beispiel #19
0
 /// <summary>
 /// Gets or sets the <see cref="T"/> at the specified index.
 /// </summary>
 /// <value>
 /// The <see cref="T"/>.
 /// </value>
 /// <param name="index">The index.</param>
 /// <returns></returns>
 public T this[int index]
 {
     get
     {
         var value = RedisDb.ListGetByIndex(RedisKey, index);
         return(value.HasValue ? Serializer.Deserialize <T>(value) : default(T));
     }
     set
     {
         RedisDb.ListSetByIndex(RedisKey, index, Serializer.Serialize(value));
     }
 }
Beispiel #20
0
 /// <summary>
 /// Inserts the asynchronous.
 /// </summary>
 /// <param name="tran">The tran.</param>
 /// <param name="index">The index.</param>
 /// <param name="item">The item.</param>
 /// <returns></returns>
 /// <exception cref="IndexOutOfRangeException"></exception>
 public async Task InsertAsync(ITransaction tran, int index, T item)
 {
     if (RedisDb.ListLength(RedisKey) > index)
     {
         var before = RedisDb.ListGetByIndex(RedisKey, index);
         await tran.ListInsertBeforeAsync(RedisKey, before, Serializer.Serialize(item));
     }
     else
     {
         throw new IndexOutOfRangeException($"Index: '{index}' for Redis list: '{RedisKey}' is out of range.");
     }
 }
Beispiel #21
0
 /// <summary>
 /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1" /> at the specified index.
 /// </summary>
 /// <param name="index">The zero-based index at which <paramref name="item" /> should be inserted.</param>
 /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1" />.</param>
 public void Insert(int index, T item)
 {
     if (RedisDb.ListLength(RedisKey) > index)
     {
         var before = RedisDb.ListGetByIndex(RedisKey, index);
         RedisDb.ListInsertBefore(RedisKey, before, Serializer.Serialize(item));
     }
     else
     {
         throw new IndexOutOfRangeException($"Index: '{index}' for Redis list: '{RedisKey}' is out of range.");
     }
 }
Beispiel #22
0
 public RedisOperationLogChangeNotifier(
     RedisOperationLogChangeTrackingOptions <TDbContext> options,
     AgentInfo agentInfo,
     IServiceProvider services)
     : base(services)
 {
     Options   = options;
     AgentInfo = agentInfo;
     RedisDb   = Services.GetService <RedisDb <TDbContext> >() ?? Services.GetRequiredService <RedisDb>();
     RedisPub  = RedisDb.GetPub(options.PubSubKey);
     Log.LogInformation("Using pub/sub key = '{Key}'", RedisPub.FullKey);
 }
Beispiel #23
0
        /// <summary>
        /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param>
        /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
        public void CopyTo(KeyValuePair <TKey, TValue>[] array, int arrayIndex)
        {
            var values = RedisDb.HashGetAll(RedisKey);

            for (var i = 0; i < values.Length; i++)
            {
                var key   = KeySerializer.Deserialize <TKey>(values[i].Name);
                var value = ValueSerializer.Deserialize <TValue>(values[i].Value);

                array[i + arrayIndex] = new KeyValuePair <TKey, TValue>(key, value);
            }
        }
Beispiel #24
0
 /// <summary>
 /// Gets or sets the <see cref="TValue"/> with the specified key.
 /// </summary>
 /// <value>
 /// The <see cref="TValue"/>.
 /// </value>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 public TValue this[TKey key]
 {
     get
     {
         var redisValue = RedisDb.HashGet(RedisKey, KeySerializer.Serialize(key));
         return(redisValue.IsNull ? default(TValue) : ValueSerializer.Deserialize <TValue>(redisValue));
     }
     set
     {
         Add(key, value);
     }
 }
Beispiel #25
0
        public ResponseModel <List <BusinessGroupDTO> > GetBusinessGroup()
        {
            var result = new ResponseModel <List <BusinessGroupDTO> >();

            result.message     = "";
            result.error_code  = Result.SUCCESS;
            result.total_count = 0;
            List <BusinessGroupDTO> list = new List <BusinessGroupDTO>();
            //查询缓存数据
            string key       = "BusinessGroupApi_GetBusinessGroup";
            string key_count = "BusinessGroupApi_GetBusinessGroup_ListCount";

            if (RedisDb._redisHelper_11().KeyExists(key))
            {
                var data = RedisDb._redisHelper_11().StringGet <List <BusinessGroupDTO> >(key);
                result.data        = data;
                result.total_count = RedisDb._redisHelper_11().StringGet <int>(key_count);
            }
            else
            {
                int total_count = 0;
                //list.comment_list = new List<CommentDTO>();
                //var model = _businessCommentService.GetPageListByUserId(User_Id, Level_Id, Page_Index, Page_Size, out total_count);
                var getlist = _businessGroupService.GetAll().OrderBy(c => c.Sort).ToList();
                if (getlist != null && getlist.Count > 0)
                {
                    foreach (var item in getlist)
                    {
                        if (item.Name == "电影")
                        {
                            continue;
                        }
                        list.Add(
                            new BusinessGroupDTO()
                        {
                            business_group_id = item.BusinessGroupId,
                            name                   = item.Name,
                            sort                   = item.Sort,
                            base_image_id          = item.BaseImage == null ? 0 : item.BaseImage.BaseImageId,
                            path                   = item.BaseImage == null ? "" : item.BaseImage.Source + item.BaseImage.Path,
                            BusinessGroupImageList = BusinessGroupImageToDTO(item.BusinessGroupImageList)
                        });
                    }
                    total_count = list.Count;
                }
                result.data        = list;
                result.total_count = total_count;
                //设置缓存数据
                RedisDb._redisHelper_11().StringSet(key, list, RedisConfig._defaultExpiry);
                RedisDb._redisHelper_11().StringSet(key_count, total_count, RedisConfig._defaultExpiry);
            }
            return(result);
        }
Beispiel #26
0
 /// <summary>
 /// AddTokenToBlacklist
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="accessToken"></param>
 public static void AddTokenToBlacklist(string userName, string accessToken, string refreshToken)
 {
     try
     {
         string key = string.Format(CacheKeys.AUTHEN, userName.ToUpper());
         RedisDb.saveTokenToBlackRedis(key, accessToken);
     }
     catch (Exception ex)
     {
         //Helper.SetCustomLog(string.Concat("Exception: ", ex.ToString()));
     }
 }
Beispiel #27
0
        protected override async Task InvokUnlockScriptAsync(int leaseTime)
        {
            var preparedScript = LuaScriptLoader.GetScript(LockScript.WRITE_LOCK_RELEASE);

            var result = await RedisDb.ScriptEvaluateAsync(preparedScript, new
            {
                lock_key        = LockKey,
                channel         = ChannelName,
                read_unlock_msg = LockPubSub.READ_UNLOCK_MESSAGE,
                expire          = leaseTime,
                lock_id         = LockId
            });
        }
Beispiel #28
0
        /// <summary>
        /// Gets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key whose value to get.</param>
        /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param>
        /// <returns>
        /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key; otherwise, false.
        /// </returns>
        public bool TryGetValue(TKey key, out TValue value)
        {
            var redisValue = RedisDb.HashGet(RedisKey, KeySerializer.Serialize(key));

            if (redisValue.IsNull)
            {
                value = default(TValue);
                return(false);
            }

            value = ValueSerializer.Deserialize <TValue>(redisValue);
            return(true);
        }
Beispiel #29
0
        /// <summary>
        /// 刷新缓存
        /// </summary>
        private void ReloadCache()
        {
            _isReloading = true;
            WriteColorLine($"正在执行缓存刷新", ConsoleColor.Green);
            Thread.Sleep(2 * 1000);

            RedisDb.Set(_cacheList[_reloadCache], $"[{DateTime.Now}]{_cacheList[_reloadCache]}");
            RedisDb.Expire(_cacheList[_reloadCache], 30);

            _nextReloadTime = DateTime.Now.AddSeconds(1);
            WriteColorLine($"执行缓存刷新完毕", ConsoleColor.Green);
            _isReloading = false;
        }
Beispiel #30
0
        public FilmService()
        {
            log = LogManager.GetLogger(this.GetType());
            RedisDb.InitDb();
            this.db = RedisDb.GetRedisDb;
            rooturl = ConfigurationManager.AppSettings["rooturl"];
            int pos = rooturl.LastIndexOf("/");

            page_baseurl = rooturl.Substring(0, pos + 1);
            Regex reg = new Regex("(?<domain>.*://www.+?/.*?)");

            domainurl = reg.Match(rooturl).Groups["domain"].Value;
            domainurl = domainurl.Remove(domainurl.Length - 1);
        }
Beispiel #31
0
        private void RedisSubscribe(Action<string, string> action, string mqpath, string channelname)
        {
            var manager = new XXF.Redis.RedisManager();
            redisDb = manager.CreateClient(RedisServerIp.Split(':')[0], Convert.ToInt32(RedisServerIp.Split(':')[1]), "");
            using (var subscription = redisDb.GetClient().CreateSubscription())
            {
                subscription.OnSubscribe = channel =>
                {

                    //订阅事件
                };
                subscription.OnUnSubscribe = channel =>
                {

                    //退订事件
                };
                subscription.OnMessage = (channel, msg) =>
                {
                    try
                    {
                        if (msg == "RedisNetCommandListener-Close" || isdisposeing==true)//关闭通道
                        {
                            try { subscription.UnSubscribeFromChannels(channel); }
                            catch { }
                        }
                        else
                        {
                            if (action != null)
                                action.Invoke(channel, msg);
                        }
                    }
                    catch (Exception exp)
                    {
                        ErrorLogHelper.WriteLine(-1, mqpath, "RedisSubscribe", string.Format("MQredis订阅通信消息,通道:{1},处理消息{0},订阅名:{2}出错", msg.NullToEmpty(), channelname, Name), exp);
                    }
                };
                subscription.SubscribeToChannels(channelname);
            }
        }
Beispiel #32
0
        private void CloseRedisClient()
        {
            try
            {
                if (redisDb != null)
                {

                    if (redisDb.GetClient() != null)
                    {
                        redisDb.GetClient().Quit();
                    }
                    //redisDb.Dispose();
                    redisDb = null;
                }
            }
            catch (Exception exp)
            { }
        }