Beispiel #1
0
 public bool SortedSetIncrement(string key, string member, double score, int cacheTime = 0)
 {
     _client.ZIncrBy(key, member, score);
     if (cacheTime > 0)
     {
         var expiry = cacheTime * 60;
         return(_client.Expire(key, expiry));
     }
     return(true);
 }
Beispiel #2
0
        private void Refresh(string key, DateTimeOffset?absExpr, TimeSpan?sldExpr)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            // Note Refresh has no effect if there is just an absolute expiration (or neither).
            TimeSpan?expr = null;

            if (sldExpr.HasValue)
            {
                if (absExpr.HasValue)
                {
                    var relExpr = absExpr.Value - DateTimeOffset.Now;
                    expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
                }
                else
                {
                    expr = sldExpr;
                }
                _redisClient.Expire(key, expr ?? TimeSpan.Zero);
                // TODO: Error handling
            }
        }
Beispiel #3
0
        /// <summary>
        /// 取出队列,全部处理,为空后退出
        /// </summary>
        /// <returns></returns>
        private async Task <bool> Read()
        {
            var id = client.RPopLPush(jobList, bakList);

            if (string.IsNullOrEmpty(id))
            {
                return(false);
            }

            var key   = $"msg:{Service.ServiceName}:{id}";
            var guard = $"guard:{Service.ServiceName}:{id}";

            if (!await client.SetNxAsync(guard, "Guard"))
            {
                await Task.Delay(RedisOption.Instance.MessageLockTime);

                return(true);
            }
            client.Expire(guard, RedisOption.Instance.MessageLockTime);

            var str = client.Get(key);

            if (string.IsNullOrEmpty(str))
            {
                logger.Warning(() => $"ReadList key empty.{key}");
                await client.DelAsync(key);

                await client.LRemAsync(bakList, 0, id);

                await client.DelAsync(guard);

                return(true);
            }
            IInlineMessage item;

            try
            {
                item = SmartSerializer.ToMessage(str);
            }
            catch (Exception ex)
            {
                logger.Warning(() => $"ReadList deserialize error.{ex.Message }.{key} =>{str}");
                await client.DelAsync(key);

                await client.LRemAsync(bakList, 0, id);

                await client.DelAsync(guard);

                return(true);
            }
            //item.Trace ??= TraceInfo.New(item.ID);
            item.Service = Service.ServiceName;

            _ = MessageProcessor.OnMessagePush(Service, item, true, null);

            return(true);
        }
Beispiel #4
0
        private void SetKeyExpiration(CSRedisClient client, string cacheKey, Func <ICacheItemExpiration> expiration)
        {
            if (!client.Exists(cacheKey))
            {
                return;
            }

            var expiry = GetExpirationTime(expiration);

            if (expiry != null)
            {
                client.Expire(cacheKey, (int)expiry.Value.TotalSeconds);
            }
            else
            {
                client.Expire(cacheKey, TimeSpan.MaxValue);
            }
        }
Beispiel #5
0
        private void SetKeyExpiration(CSRedisClient client, string cacheKey, Func <ICacheItemExpiration> expiration)
        {
            var expiry = GetExpirationTime(expiration);

            if (expiry != null)
            {
                client.Expire(cacheKey, (int)expiry.Value.TotalSeconds);
            }
        }
Beispiel #6
0
 /// <summary>
 /// 为给定 key 设置过期时间
 /// </summary>
 /// <param name="key"></param>
 /// <param name="seconds"></param>
 /// <returns></returns>
 public static new bool Expire(string key, int seconds)
 {
     try
     {
         return(_redisManager.Expire(key, seconds));
     }
     catch (Exception)
     {
         return(false);
     }
 }
Beispiel #7
0
 public bool SetNx(string key, long time, double expireMS)
 {
     if (csRedisClient.SetNx(key, time))
     {
         if (expireMS > 0)
         {
             csRedisClient.Expire(key, TimeSpan.FromMilliseconds(expireMS));
         }
         return(true);
     }
     return(false);
 }
        public void AddOrIncrementWithExpiration(IThrottleKey key, Limiter limiter)
        {
            string id = CreateThrottleKey(key, limiter);

            //设置增量
            long result = CSRedis.IncrBy(id);

            //设置过期时间
            if (result == 1)
            {
                CSRedis.Expire(id, limiter.Period);
            }
        }
Beispiel #9
0
        public static bool M5_SetNx(this CSRedisClient client, string key, object value, int expireSeconds = 1)
        {
            var pl     = client.StartPipe();
            var result = client.SetNx(key, value);

            if (result)
            {
                client.Expire(key, expireSeconds);
            }
            pl.EndPipe();

            return(result);
        }
Beispiel #10
0
        /// <summary>
        /// 异常守护
        /// </summary>
        private async Task Guard()
        {
            logger.Information("异常消息守卫已启动");
            using var client = new CSRedisClient(RedisOption.Instance.ConnectionString);
            //处理错误重新入列
            while (true)
            {
                var key = client.LPop(errList);
                if (string.IsNullOrEmpty(key))
                {
                    break;
                }

                logger.Debug(() => $"异常消息重新入列:{key}");
                client.LPush(jobList, key);
            }
            //非正常处理还原
            while (ZeroAppOption.Instance.IsAlive)
            {
                await Task.Delay(RedisOption.Instance.GuardCheckTime, token);

                try
                {
                    var key = await client.LPopAsync(bakList);

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

                    var guard = $"guard:{Service.ServiceName}:{key}";
                    if (await client.SetNxAsync(guard, "Guard"))
                    {
                        client.Expire(guard, RedisOption.Instance.MessageLockTime);
                        logger.Debug(() => $"超时消息重新入列:{key}");
                        await client.LPushAsync(jobList, key);

                        await client.DelAsync(guard);
                    }
                }
                catch (Exception ex)
                {
                    logger.Information(() => $"异常消息守卫错误.{ex.Message }");
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// 开启分布式锁,若超时返回null
        /// </summary>
        /// <param name="name">锁名称</param>
        /// <param name="timeoutSeconds">超时(秒)</param>
        /// <returns></returns>
        public static CSRedisClientLock Lock(string name, int timeoutSeconds)
        {
            name = $"CSRedisClientLock:{name}";
            var startTime = DateTime.Now;

            while (DateTime.Now.Subtract(startTime).TotalSeconds < timeoutSeconds)
            {
                if (cs.SetNx(name, "1") == true)
                {
                    cs.Expire(name, TimeSpan.FromSeconds(timeoutSeconds));
                    return(new CSRedisClientLock {
                        Name = name, _client = cs
                    });
                }
                Thread.CurrentThread.Join(3);
            }
            return(null);
        }
 /// <summary>
 /// 对key加锁
 /// </summary>
 /// <param name="key"></param>
 /// <param name="expireSecond"></param>
 /// <returns></returns>
 public bool LockAsync(string key, int expireSecond)
 {
     if (_client.SetNx(key, (DateTime.Now.Ticks / 10000) + expireSecond * 1000))
     {
         _client.Expire(key, expireSecond);
         return(true);
     }
     else
     {
         var value = _client.Get(key);
         if (!string.IsNullOrEmpty(value))
         {
             long lastValue = 0;
             if (long.TryParse(value, out lastValue))
             {
                 if (lastValue > DateTime.Now.Ticks / 10000)
                 {
                     return(false);
                 }
                 else
                 {
                     _client.Del(key);
                     return(false);
                 }
             }
             else
             {
                 _client.Del(key);
                 return(false);
             }
         }
         else
         {
             _client.Del(key);
             return(false);
         }
     }
 }
 public bool RenameKey(string key, string newKey, int second)
 {
     return(csClient.Rename(key, newKey) && csClient.Expire(newKey, second));
 }
Beispiel #14
0
 public bool KeyExpire(string key, TimeSpan expiry) => _instance.Expire(key, expiry);