Exemple #1
0
        private static void ToCacheList(List <SearchWord> sWordList)
        {
            if (sWordList == null)
            {
                return;
            }

            using (IRedisClient redisCli = Common.Common.RedisPool.GetClient())
            {
                //添加到list中十分钟后失效用于及时应用
                var list = sWordList.Select(l => l.key).ToList <string>();
                redisCli.AddRangeToList(Common.ConfigSettings.RedisListKey, list);

                if (redisCli.GetTimeToLive(Common.ConfigSettings.RedisListKey).TotalSeconds < 0)
                {
                    redisCli.ExpireEntryIn(Common.ConfigSettings.RedisListKey, new TimeSpan(0, 10, 0));
                }


                //添加到有序集合中用于统计
                foreach (var item in sWordList)
                {
                    //redisCli.AddItemToSortedSet(RedisListKey, item.key, Convert.ToInt64(item.dt.ToString("yyyyMMddHHmmss")));
                    redisCli.IncrementItemInSortedSet(Common.ConfigSettings.RedisSortListKey, item.key, 1);
                }

                if (redisCli.GetTimeToLive(Common.ConfigSettings.RedisSortListKey).TotalSeconds < 0)
                {
                    redisCli.ExpireEntryIn(Common.ConfigSettings.RedisSortListKey, new TimeSpan(24, 0, 0));
                }


                // redisCli.GetRangeWithScoresFromSortedSet(RedisListKey,;
            }
        }
        public string CreateHashMessage(string key, NotificationMessageDto msg)
        {
            //pamtimo notifikaciju koju treba da saljemo korisnicima
            string hashKey = key + ":" + MsgPostfix;

            _redis.SetEntryInHash(hashKey, "message", msg.Message);
            _redis.SetEntryInHash(hashKey, "createdAt", msg.CreatedAt.ToString());
            _redis.SetEntryInHash(hashKey, "creator", msg.Creator);
            TimeSpan timeSpan = new TimeSpan(0, 0, ttl);

            _redis.ExpireEntryIn(hashKey, timeSpan);
            return(hashKey);
        }
Exemple #3
0
        /// <summary>
        /// 存储数据到hash表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        public bool Hash_Set <T>(string key, string dataKey, T t, int?timeout = null)
        {
            IRedisClient redis = null;

            try
            {
                var manager = GetClientManager(key);
                if (manager == null)
                {
                    return(false);
                }
                redis = manager.GetClient();
                string value  = JsonUtils.SerializeObject(t);
                var    result = redis.SetEntryInHash(key, dataKey, value);
                if (timeout.HasValue && timeout.Value > 0)
                {
                    redis.ExpireEntryIn(key, new TimeSpan(0, timeout.Value, 0));
                }
                return(result);
            }
            catch (Exception ex)
            {
                RemoveClientFromPool(key);
                Logger.Error(ex, "RedisBase.Set_Remove");
            }
            finally
            {
                if (redis != null)
                {
                    redis.Dispose();
                }
            }
            return(false);
        }
Exemple #4
0
 public void SetExprieTime(string key, System.TimeSpan ts)
 {
     using (IRedisClient _client = this.GetClient())
     {
         _client.ExpireEntryIn(key, ts);
     }
 }
Exemple #5
0
 /// <summary>
 /// 设置过期时间
 /// </summary>
 /// <param name="key"></param>
 /// <param name="time"></param>
 /// <returns></returns>
 public static bool ExpireEntryIn(string key, TimeSpan time)
 {
     using (IRedisClient redis = prcm.GetClient())
     {
         return(redis.ExpireEntryIn(key, time));
     }
 }
 /// <summary>
 /// 设置缓存过期
 /// </summary>
 /// <param name="key"></param>
 public static bool Item_SetExpire(string key, int timeout)
 {
     using (IRedisClient redis = prcm.GetClient())
     {
         return(redis.ExpireEntryIn(key, new TimeSpan(0, timeout, 0)));
     }
 }
Exemple #7
0
 public void Expire(string key, int seconds)
 {
     using (IRedisClient Redis = RedisManager.GetClient())
     {
         Redis.ExpireEntryIn(key, new TimeSpan(0, 0, seconds));
     }
 }
        /// <summary>
        /// 获取存储的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetValue <T>(string key)
        {
            using (IRedisClient client = _clientsManager.GetClient())
            {
                T   o         = default(T);
                var valueJson = client.GetValueFromHash(_name, key + "Data");

                if (valueJson == null)
                {
                    throw new NullReferenceException();
                }

                if (!IsImmutable(typeof(T)))
                {
                    o = JsonSerializer.DeserializeFromString <T>(valueJson);
                }
                else
                {
                    o = (T)Convert.ChangeType(valueJson, typeof(T));
                    try
                    {
                        o = (T)Convert.ChangeType(valueJson, typeof(T));
                    }
                    catch (Exception)
                    {
                        o = default(T);
                    }
                }

                client.ExpireEntryIn(_name, _expiresIn);
                return(o);
            }
        }
        /// <summary>
        /// 从Redis内获取值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private object Get(string key)
        {
            using (IRedisClient client = _clientsManager.GetClient())
            {
                object o         = null;
                var    typeName  = client.GetValueFromHash(_name, key + "Type");
                var    valueJson = client.GetValueFromHash(_name, key + "Data");

                if (typeName == null || valueJson == null)
                {
                    throw new NullReferenceException();
                }

                var type = Type.GetType(typeName, true);

                if (!IsImmutable(type))
                {
                    o = ServiceStack.Text.JsonSerializer.DeserializeFromString(valueJson, type);
                }
                else
                {
                    o = Convert.ChangeType(valueJson, type);
                }
                client.ExpireEntryIn(_name, _expiresIn);
                return(o);
            }
        }
Exemple #10
0
        /// <summary>
        /// 设置缓存过期
        /// </summary>
        /// <param name="key"></param>
        /// <param name="timeout"></param>
        public bool Item_SetExpire(string key, int timeout)
        {
            IRedisClient redis = null;

            try
            {
                var manager = GetClientManager(key);
                if (manager == null)
                {
                    return(true);
                }
                redis = manager.GetClient();
                return(redis.ExpireEntryIn(key, new TimeSpan(0, timeout, 0)));
            }
            catch (Exception ex)
            {
                RemoveClientFromPool(key);
                Logger.Error(ex, "RedisBase.Item_SetExpire");
            }
            finally
            {
                if (redis != null)
                {
                    redis.Dispose();
                }
            }
            return(false);
        }
Exemple #11
0
 /// <summary>
 /// 调整过期时间
 /// </summary>
 /// <returns></returns>
 public bool Expire(string key, TimeSpan expire)
 {
     lock (m_w)
     {
         return(m_w.ExpireEntryIn(key, expire));
     }
 }
Exemple #12
0
 /// <summary>
 /// 设置缓存过期
 /// </summary>
 /// <param name="key"></param>
 /// <param name="expiredTime"></param>
 public static void Expire(string key, TimeSpan expiredTime)
 {
     using (IRedisClient redis = prcm.GetClient())
     {
         redis.ExpireEntryIn(key, expiredTime);
     }
 }
Exemple #13
0
 /// <summary>
 /// 设置过期时间
 ///
 /// 2016-02-24  15:26:30
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="sp">时间间隔</param>
 public void SetKeyExpire(string key, TimeSpan sp)
 {
     using (IRedisClient client = RedisManager.GetRedisWriteClient())
     {
         client.ExpireEntryIn(key, sp);
     }
 }
Exemple #14
0
 public static void SortedSet_SetExpire(string key, TimeSpan timeSpan)
 {
     using (IRedisClient redis = prcm.GetClient())
     {
         redis.ExpireEntryIn(key, timeSpan);
     }
 }
Exemple #15
0
 /// <summary>
 /// 为key添加多个值,并设置过期时间
 /// </summary>
 public void Add(string key, List <string> values, TimeSpan sp)
 {
     using (IRedisClient Core = CreateRedisClient())
     {
         Core.AddRangeToList(key, values);
         Core.ExpireEntryIn(key, sp);
     }
 }
Exemple #16
0
 /// <summary>
 /// 从右侧向list中添加值,并设置过期时间
 /// </summary>
 public void RPush(string key, string value, TimeSpan sp)
 {
     using (IRedisClient Core = CreateRedisClient())
     {
         Core.PrependItemToList(key, value);
         Core.ExpireEntryIn(key, sp);
     }
 }
        /// <summary>
        ///  设置指定key的过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="expireIn"></param>
        public bool ExpireEntryIn(string key, TimeSpan expireIn)
        {
            bool succeed = false;

            using (IRedisClient client = redisPool.GetClient())
            {
                succeed = client.ExpireEntryIn(key, expireIn);
            }

            return(succeed);
        }
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string identifier = GetUserIdentifier(request);
            string cacheKey   = GetCacheKey(identifier);

            if (string.IsNullOrEmpty(identifier))
            {
                return(CreateResponse(request, HttpStatusCode.Forbidden, "Could not identify client."));
            }

            long maxRequests  = _maxRequestsForUserIdentifier(identifier);
            long requestCount = 0;

            using (IRedisClient client = _clientsManager.GetClient()) {
                requestCount = client.IncrementValueBy(cacheKey, 1);
                if (requestCount == 1)
                {
                    client.ExpireEntryIn(cacheKey, _period);
                }
            }

            Task <HttpResponseMessage> response = null;

            if (requestCount > maxRequests)
            {
                response = CreateResponse(request, HttpStatusCode.Conflict, _message);
            }
            else
            {
                response = base.SendAsync(request, cancellationToken);
            }

            return(response.ContinueWith(task => {
                long remaining = maxRequests - requestCount;
                if (remaining < 0)
                {
                    remaining = 0;
                }

                HttpResponseMessage httpResponse = task.Result;
                httpResponse.Headers.Add("RateLimit-Limit", maxRequests.ToString());
                httpResponse.Headers.Add("RateLimit-Remaining", remaining.ToString());

                return httpResponse;
            }));
        }
Exemple #19
0
 /// <summary>
 /// 根据IEnumerable数据添加链表
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="listId"></param>
 /// <param name="values"></param>
 /// <param name="timeout"></param>
 public void AddList <T>(string listId, IEnumerable <T> values, int timeout = 0)
 {
     using (_redis = GetClient())
     {
         lock (accessLock)
         {
             IRedisTypedClient <T> iredisClient = _redis.As <T>();
             var redisList = iredisClient.Lists[ConvertKey(listId)];
             redisList.AddRange(values);
             iredisClient.Save();
             if (timeout > 0)
             {
                 SecondsTimeOut = timeout;
             }
             _redis.ExpireEntryIn(ConvertKey(listId), new TimeSpan(0, 0, 0, SecondsTimeOut));
         }
     }
 }
Exemple #20
0
 /// <summary>
 /// 添加单个实体到链表中
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="listId"></param>
 /// <param name="item"></param>
 /// <param name="timeout"></param>
 public void AddEntityToList <T>(string listId, T item, int timeout = 0)
 {
     using (_redis = GetClient())
     {
         lock (AccessLock)
         {
             IRedisTypedClient <T> iredisClient = _redis.As <T>();
             var redisList = iredisClient.Lists[ConvertKey(listId)];
             redisList.Add(item);
             iredisClient.Save();
             if (timeout > 0)
             {
                 SecondsTimeOut = timeout;
             }
             _redis.ExpireEntryIn(ConvertKey(listId), new TimeSpan(0, 0, SecondsTimeOut));
         }
     }
 }
Exemple #21
0
        private void HandleHostMasterRole(IRedisClient r)
        {
            var currentMaster      = r.Get <RedisHostMasterInfo>(RedisHostKey);
            var hasTakenMasterRole = false;

            if (currentMaster == null)//try to become master
            {
                if (r.SetValueIfNotExists(RedisHostKey, HostMasterInfo.ToJson()))
                {
                    IsHostMaster       = true;
                    hasTakenMasterRole = true;
                    r.ExpireEntryIn(RedisHostKey, NodeTimeoutPeriod); //give an extra 1 second to refresh.
                }
                else
                {
                    //we lost, oh well.
                    IsHostMaster = false;
                }
            }
            if (IsHostMaster) //We think we are master
            {
                if (currentMaster == null)
                {
                    currentMaster = r.Get <RedisHostMasterInfo>(RedisHostKey);
                }
                if (currentMaster.NodeId.Equals(NodeId))
                {                                                                                                        //Yep its ours, update & kick timeout
                    OnHostRefreshActions.ForEach(a => a());                                                              //run any registered actions for Host
                    r.Set(RedisHostKey, HostMasterInfo, NodeTimeoutPeriod);
                    r.AddItemToSortedSet("{0}:hosts:lastseen".Fmt(RedisPrefix), HostName, DateTime.UtcNow.ToUnixTime()); //score is unixtime UTC useful to figure out when a host dropped out
                    if (hasTakenMasterRole)
                    {
                        Log.DebugFormat("NodeId:{0} has taken HostMaster role", NodeId, currentMaster.NodeId);
                    }
                }
                else
                {
                    IsHostMaster = false;
                    Log.DebugFormat("NodeId:{0} has lost HostMaster role to {1}", NodeId, currentMaster.NodeId);
                }
            }
        }
Exemple #22
0
        public bool TryGetValue <T>(string key, out T val)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            key = GetKey(key);

            using (FClient.AcquireLock($"{key}_lock", TimeSpan.FromSeconds(10)))
            {
                Entry <T>?entry = FClient.Get <Entry <T> >(key);
                if (entry != null)
                {
                    FClient.ExpireEntryIn(key, entry.ExpiresIn);
                    val = entry.Data;
                    return(true);
                }
            }

            val = default !;
 /// <summary>
 /// 调整过期时间
 /// </summary>
 /// <returns></returns>
 public bool Expire(TimeSpan expire)
 {
     return(redis.ExpireEntryIn(Key, expire));
 }
Exemple #24
0
 public void Expire(string chave, TimeSpan tempo)
 {
     redisClient.ExpireEntryIn(chave, tempo);
 }
Exemple #25
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="key"></param>
 /// <param name="seconds"></param>
 public void SetExpired(string key, int seconds)
 {
     using (_redis = GetClient())
         _redis.ExpireEntryIn(ConvertKey(key), new TimeSpan(0, 0, 0, seconds));
 }