public override void Log(IRequest request, object requestDto, object response, TimeSpan requestDuration)
        {
            var requestType = requestDto != null?requestDto.GetType() : null;

            if (ExcludeRequestType(requestType))
            {
                return;
            }

            using (var redis = redisManager.GetClient())
            {
                var redisLogEntry = redis.As <RequestLogEntry>();

                var entry = CreateEntry(request, requestDto, response, requestDuration, requestType);
                entry.Id = redisLogEntry.GetNextSequence();

                var key      = UrnId.Create <RequestLogEntry>(entry.Id).ToLower();
                var nowScore = DateTime.UtcNow.ToUnixTime();

                using (var trans = redis.CreateTransaction())
                {
                    trans.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, key, nowScore));
                    trans.QueueCommand(r => r.Store(entry));

                    if (loggerCapacity != null)
                    {
                        trans.QueueCommand(r => r.RemoveRangeFromSortedSet(SortedSetKey, 0, -loggerCapacity.Value - 1));
                    }

                    trans.Commit();
                }
            }
        }
Exemple #2
0
 public void Set <T>(string key, T value, TimeSpan expiresIn)
 {
     using (var client = _redisClientsManager.GetClient())
     {
         client.Set(key, value, expiresIn);
     }
 }
Exemple #3
0
        public BotInstanceData GetBotInstanceData(string id)
        {
            using var redis = _redisManager.GetClient();
            var redisBotInstanceData = redis.As <BotInstanceData>();

            return(redisBotInstanceData.GetHash <string>("BOT_INSTANCE_DATA").FirstOrDefault(i => i.Key == id).Value);
        }
 public T Get <T>(string key)
 {
     using (var redis = _redisCacheManager.GetClient())
     {
         return(redis.Get <T>(key));
     }
 }
        private IRedisClient GetClientAndWatch(string key)
        {
            var client = _clientsManager.GetClient();

            client.Watch(key);
            return(client);
        }
        public IApiSecrets GetApiSecret(string secretId)
        {
            using var redis = _redisManager.GetClient();
            var redisBotInstanceData = redis.As <IApiSecrets>();

            return(redisBotInstanceData.GetHash <string>("SECRET_DATA").FirstOrDefault(i => i.Key == secretId).Value);
        }
Exemple #7
0
        public bool TryAcquireTimedLock(string resourceName)
        {
            if (string.IsNullOrWhiteSpace(resourceName))
            {
                throw new ArgumentException("A resource name is required", nameof(resourceName));
            }

            _resourceName = resourceName;

            using (var redisClient = _redisClientManager.GetClient() as RedisClient)
            {
                if (redisClient == null)
                {
                    return(false);
                }

                try
                {
                    // TODO: The timeout parameter
                    if (redisClient.SetValueIfNotExists($"{resourceName}", $"mutexAcquired:{DateTime.UtcNow}", TimeSpan.FromSeconds(_lockTimeoutInSeconds)))
                    {
                        return(true);
                    }

                    return(false);
                }
                catch (Exception)
                {
                    // LOG
                    return(false);
                }
            }
        }
Exemple #8
0
        public void ImportCountry(IRedisClientsManager redisManager, string countryCode)
        {
            using (var redis = redisManager.GetClient())
                using (var reader = new StreamReader(File.OpenRead(MapProjectPath($"~/App_Data/{countryCode}.txt"))))
                {
                    string line, lastState = null, lastCity = null;
                    var    results = new List <ServiceStack.Redis.RedisGeo>();
                    while ((line = reader.ReadLine()) != null)
                    {
                        var parts     = line.Split('\t');
                        var city      = parts[2];
                        var state     = parts[4];
                        var latitude  = double.Parse(parts[9]);
                        var longitude = double.Parse(parts[10]);

                        if (city == lastCity) //Skip duplicate entries
                        {
                            continue;
                        }
                        else
                        {
                            lastCity = city;
                        }

                        if (lastState == null)
                        {
                            lastState = state;
                        }

                        if (state != lastState)
                        {
                            redis.AddGeoMembers(lastState, results.ToArray());
                            lastState = state;
                            results.Clear();
                        }

                        results.Add(new ServiceStack.Redis.RedisGeo(longitude, latitude, city));
                    }
                }

            using (var redis = redisManager.GetClient())
                using (var reader =
                           new StreamReader(File.OpenRead(MapProjectPath($"~/App_Data/{countryCode}_mapping.txt"))))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.Trim().Length == 0)
                        {
                            continue;
                        }
                        var stateInfo = line.Split("\t");
                        if (stateInfo.Length != 2)
                        {
                            continue;
                        }
                        redis.Set("mapping:" + stateInfo[1].Trim(), stateInfo[0].Trim());
                    }
                }
        }
Exemple #9
0
        public void Stop()
        {
            if (Interlocked.CompareExchange(ref status, 0, 0) == WorkerStatus.Disposed)
            {
                throw new ObjectDisposedException("MQ Host has been disposed");
            }

            if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopping, WorkerStatus.Started) == WorkerStatus.Started)
            {
                Log.Debug("Stopping MQ Host...");

                //Unblock current bgthread by issuing StopCommand
                try
                {
                    using (var redis = clientsManager.GetClient())
                    {
                        Interlocked.CompareExchange(ref doOperation, WorkerOperation.Stop, doOperation);
                        redis.PublishMessage(QueueNames.TopicIn, WorkerOperation.ControlCommand);
                    }
                }
                catch (Exception ex)
                {
                    if (this.ErrorHandler != null)
                    {
                        this.ErrorHandler(ex);
                    }
                    Log.Warn("Could not send STOP message to bg thread: " + ex.Message);
                }
            }
        }
Exemple #10
0
        public void StartInsertUnix(string lp)
        {
            try
            {
                using (IRedisClient client = clientManager.GetClient()) {
                    using (var redisLocs = client.As <Loc>())
                    {
                        //for (int i = 0; i < 1; i++)//一个月
                        //{
                        for (int j = 0; j < 2000; j++)
                        {
                            //string plateNumber = (string)row["plate_number"];

                            redisLocs.Lists[lp].Add(new Loc {
                                lat = 20 * j, lng = 20, plate_number = lp, acc = true, mileage = 15 * j, time = DateTime.Now.AddMinutes(j)
                            });
                            //Id = redisLocs.GetNextSequence(),
                            //redisLocs.Store(new Loc {  lat = (double)row["lat"], lng = (double)row["lng"], plate_number = (string)row["plate_number"], acc = (bool)row["acc"], mileage = (float)row["mileage"], time = ConvertFromDateTimeOffset((DateTimeOffset)row["time"]) });//);
                            Console.WriteLine("insert :" + lp);
                        }
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
                Console.Read();
            }
        }
Exemple #11
0
 public long Increment(string key, int amount = 1)
 {
     using (var redis = redisManager.GetClient())
     {
         return(redis.IncrementValueBy("seq:" + key, amount));
     }
 }
 public bool IsTracked(Guid id)
 {
     using (var redis = _manager.GetClient())
     {
         return(redis.ContainsKey(id.ToString()));
     }
 }
 public void Remove(string key)
 {
     using (var redisClient = redisClientsManager.GetClient())
     {
         redisClient.RemoveEntryFromHash(PiranhaHash, key);
     }
 }
Exemple #14
0
        public string Decrypt(string encryptId)
        {
            var encryptionEntities = _session.GetByEncryptionId(encryptId);

            if (!encryptionEntities.Any())
            {
                return(null);
            }
            var requestId    = Guid.NewGuid();
            var challengeIds = new List <string> ();

            foreach (var entity in encryptionEntities)
            {
                var id = Guid.NewGuid();
                challengeIds.Add(id.ToString());
                _challengeBL.CreateChallenge(new ChallengeEntity {
                    Id           = id,
                    Challenge    = GenerateChallenge(encryptId, entity.UserId),
                    UserId       = entity.UserId,
                    Ttl          = TimeSpan.FromHours(1),
                    EncryptionId = entity.Id
                });
            }

            // store requestId in memcache with the keys that must be decoded
            using (var client = _redisClients.GetClient()) {
                client.Set(string.Format("request_{0}", requestId), string.Join(",", challengeIds));
            }
            return(requestId.ToString());
        }
Exemple #15
0
 //--- Methods ---
 public ChallengeEntity GetChallengeForUserId(int id)
 {
     using (var client = _redisManager.GetClient()) {
         var challenges    = client.As <ChallengeEntity> ();
         var allChallenges = challenges.GetAll();
         return(allChallenges.FirstOrDefault(x => x != null && x.UserId == id));
     }
 }
Exemple #16
0
 public MovieProjection GetById(object key)
 {
     using (var client = _clientsManager.GetClient())
     {
         var typedClient = client.As <MovieProjection>();
         return(typedClient.GetById(key));
     }
 }
 ///<summary>
 /// Gets the current value of the counter.
 ///</summary>
 public int GetCount()
 {
     using (IRedisClient rclient = _RCManager.GetClient())
     {
         var r = rclient.Get <int>(Key);
         return(r);
     }
 }
Exemple #18
0
 public void Add(Staff staff)
 {
     using (var redis = _redisclient.GetClient())
     {
         redis.Set(staff.Id.ToString(), JsonConvert.SerializeObject(staff));
         var unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
         redis.Set($"t{staff.Id}", unixTimestamp.ToString());
     }
 }
Exemple #19
0
 public Position Get(int id)
 {
     using (var redis = _redisManager.GetClient())
     {
         return(redis.ContainsKey(id.ToString()) ?
                Position.Parse(redis.Get <string>(id.ToString())) :
                null);
     }
 }
 public Task DequeueEventAsync(long id)
 {
     using (IRedisClient redis = clientsManager.GetClient())
     {
         var eventMessageClient = redis.As <ServerEventMessageEntity>();
         var entity             = eventMessageClient.GetById(id);
         eventMessageClient.Lists[NCORE_EVENT_LIST].Remove(entity);
     }
     return(Task.CompletedTask);
 }
 public IEnumerable <MovieProjection> Get()
 {
     using (var client = _clientsManager.GetClient())
     {
         var typedClient = client.As <MovieProjection>();
         return(typedClient
                .GetAll()
                .OrderBy(m => m.Title));
     }
 }
        public void TestGetCount()
        {
            using (var rclient = _rcm.GetClient())
            {
                rclient.Set("count", 3);
            }

            int cv = rc.GetCount();

            Assert.True(cv == 3);
        }
Exemple #23
0
        public bool IsInCache(string key)
        {
            bool isInCache = false;

            using (var client = _redisClientManager.GetClient())
            {
                isInCache = client.ContainsKey(key);
            }

            return(isInCache);
        }
Exemple #24
0
        public Task <string> GetObjectAsync(string ObjectType, string ObjectId)
        {
            var    Id = GetId(ObjectType, ObjectId);
            string result;

            using (IRedisClient redis = clientsManager.GetClient())
            {
                result = redis.GetValue(Id);
            }
            return(Task.FromResult(result));
        }
 public ITicketStatus GetTicketStatus(int operatorId, string code, DateTime departureDate, string departureTime)
 {
     using (var client = _clientManager.GetClient())
     {
         var key   = RedisTicketStatusExtensions.GetTicketStatusKey(operatorId, departureDate, departureTime);
         var value = client.GetValueFromHash(key, code.Trim());
         return(new TicketStatus()
         {
             Status = !string.IsNullOrEmpty(value)  ? Convert.ToInt32(value) : (int)TicketStatusConstant.Available
         });
     }
 }
 public Task RunClient(Int32 id, CancellationToken cancel)
 {
     using (var client = _pool.GetClient())
         using (var pipeline = client.CreatePipeline())
         {
             pipeline.QueueCommand(r => r.GetAllItemsFromSet("testkeySSE"));
             pipeline.QueueCommand(r => r.GetAllItemsFromSet("testkeySSE2"));
             pipeline.QueueCommand(r => r.Get <String>("testkeySSE3"));
             pipeline.Flush();
         }
     return(Task.FromResult <Object>(null));
 }
        public Task <PunModel> AddPun(PunViewModel punVm)
        {
            var pun = PunModel.From(punVm);

            pun.Id = Guid.NewGuid();
            return(Task.Run(() => {
                using (var redis = _redisManager.GetClient())
                {
                    redis.AddItemToList(LIST_ID, JsonSerializer.Serialize(pun));
                }
                return pun;
            }));
        }
 public void Add(string key, object value)
 {
     using (var Redis = RedisClientManager.GetClient())
     {
         try
         {
             Redis.Add(key, value);
             Redis.IncrementValue(COUNT);
         }
         catch (RedisException ex)
         {
             LogManager.GetLogger("ErrorLogger").Error(string.Format("{0}\r\n{1}", ex.Message, ex.StackTrace));
         }
     }
 }
Exemple #29
0
        public void ProcessRequest_RegistersNewScript_IfNoneInConfig(string sha1)
        {
            var mockHttpRequest = new MockHttpRequest();

            A.CallTo(() => limitProvider.GetRateLimitScriptId()).Returns(sha1);
            var client = A.Fake <IRedisClient>();

            A.CallTo(() => redisManager.GetClient()).Returns(client);

            var feature = GetSut();

            feature.ProcessRequest(mockHttpRequest, new MockHttpResponse(), null);

            A.CallTo(() => client.LoadLuaScript(A <string> .Ignored)).MustHaveHappened();
        }
		private static void UseClientAsync(IRedisClientsManager manager, int clientNo)
		{
			using (var client = manager.GetClient())
			{
				UseClient(client, clientNo);
			}
		}
        public AddReaction ProcessImage(ImageDownloaded image)
        {
            using (var client = redis.GetClient()){
                string watchkey = $"{RedisPaths.WatchedContent}:{image.MessageId}";
                var    result   = http.GetAsync($"http://detector:5000/wopr?id={image.MessageId}").Result;
                Console.WriteLine($"{image.MessageId} - {result.StatusCode}");
                if (result.IsSuccessStatusCode)
                {
                    var json = result.Content.ReadAsStringAsync().Result;
                    client.SetRangeInHash(watchkey, new KeyValuePair <string, string>[] {
                        new KeyValuePair <string, string>("status", "seen"),
                        new KeyValuePair <string, string>("result", json)
                    });

                    var classify = JsonSerializer.Deserialize <ClassifyResult>(json);

                    string classname = Convert.ToDouble(classify.predictions[0][1].ToString()) > Convert.ToDouble(classify.predictions[1][1].ToString()) ? classify.predictions[0][0].ToString() : classify.predictions[1][0].ToString();
                    return(new AddReaction()
                    {
                        Timestamp = DateTime.UtcNow,
                        MessageId = image.MessageId,
                        ChannelId = image.ChannelId,
                        Emote = classname == "unicorn" ? Emotes.WhiteCheckMark : Emotes.NoEntry
                    });
                }
                else
                {
                    return(null);
                }
            }
        }
Exemple #32
0
        static RedisHelper()
        {
            try
            {

                RedisClientManagerConfig RedisConfig = new RedisClientManagerConfig();

                RedisConfig.AutoStart = true;
                RedisConfig.MaxReadPoolSize = 60;
                RedisConfig.MaxWritePoolSize = 60;
                var hostWrite = System.Configuration.ConfigurationManager.AppSettings["RedisServerWrite"];
                var arryWrite = hostWrite.Split(';').ToList();
                var hostRead = System.Configuration.ConfigurationManager.AppSettings["RedisServerRead"];
                var arryRead = hostWrite.Split(';').ToList();
                if (arryWrite.Count > 0 && arryRead.Count > 0)
                {
                    prcm = new PooledRedisClientManager(arryWrite, arryRead, RedisConfig);
                    redisClient = prcm.GetClient();
                }
                else
                {
                    throw new Exception("连接服务器失败,请检查配置文件");
                }
            }
            catch
            {
                throw new Exception("连接服务器失败,请检查配置文件");
            }
        }
 public static string RegisterLuaScript(IRedisClientsManager clientManager)
 {
     using (var client = clientManager.GetClient())
     {
         string scriptSha1 = client.LoadLuaScript(GetLuaScript());
         return scriptSha1;
     }
 }
        private static void AssertClientManager(IRedisClientsManager redisManager, RedisEndpoint expected)
        {
            using (var readWrite = (RedisClient) redisManager.GetClient())
            using (var readOnly = (RedisClient) redisManager.GetReadOnlyClient())
            using (var cacheClientWrapper = (RedisClientManagerCacheClient) redisManager.GetCacheClient())
            {
                AssertClient(readWrite, expected);
                AssertClient(readOnly, expected);

                using (var cacheClient = (RedisClient) cacheClientWrapper.GetClient())
                {
                    AssertClient(cacheClient, expected);
                }
            }
        }
Exemple #35
0
        public ExecOnceOnly(IRedisClientsManager redisManager, string hashKey, string correlationId)
        {
            redisManager.ThrowIfNull("redisManager");
            hashKey.ThrowIfNull("hashKey");

            this.hashKey = hashKey;
            this.correlationId = correlationId;

            if (correlationId != null)
            {
                redis = redisManager.GetClient();
                var exists = !redis.SetEntryInHashIfNotExists(hashKey, correlationId, Flag);
                if (exists)
                    throw HttpError.Conflict("Request {0} has already been processed".Fmt(correlationId));
            }
        }
        public static void LogErrorInRedisIfExists(
            IRedisClientsManager redisManager, string operationName, ResponseStatus responseStatus)
        {
            //If Redis is configured, maintain rolling service error logs in Redis (an in-memory datastore)
            if (redisManager == null) return;
            try
            {
                //Get a thread-safe redis client from the client manager pool
                using (var client = redisManager.GetClient())
                {
                    //Get a client with a native interface for storing 'ResponseStatus' objects
                    var redis = client.GetTypedClient<ResponseStatus>();

                    //Store the errors in predictable Redis-named lists i.e. 
                    //'urn:ServiceErrors:{ServiceName}' and 'urn:ServiceErrors:All' 
                    var redisSeriviceErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, operationName)];
                    var redisCombinedErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, CombinedServiceLogId)];

                    //Append the error at the start of the service-specific and combined error logs.
                    redisSeriviceErrorList.Prepend(responseStatus);
                    redisCombinedErrorList.Prepend(responseStatus);

                    //Clip old error logs from the managed logs
                    const int rollingErrorCount = 1000;
                    redisSeriviceErrorList.Trim(0, rollingErrorCount);
                    redisCombinedErrorList.Trim(0, rollingErrorCount);
                }
            }
            catch (Exception suppressRedisException)
            {
                Log.Error("Could not append exception to redis service error logs", suppressRedisException);
            }
        }
		private static void UseClient(IRedisClientsManager manager, int clientNo, Dictionary<string, int> hostCountMap)
		{
			using (var client = manager.GetClient())
			{
				lock (hostCountMap)
				{
					int hostCount;
					if (!hostCountMap.TryGetValue(client.Host, out hostCount))
					{
						hostCount = 0;
					}

					hostCountMap[client.Host] = ++hostCount;
				}

				Debug.WriteLine(String.Format("Client '{0}' is using '{1}'", clientNo, client.Host));
			}
		}
        private static void InitializeEmptyRedisManagers(IRedisClientsManager redisManager, string[] masters, string[] slaves)
        {
            var hasResolver = (IHasRedisResolver)redisManager;
            hasResolver.RedisResolver.ResetMasters(masters);
            hasResolver.RedisResolver.ResetSlaves(slaves);

            using (var master = redisManager.GetClient())
            {
                Assert.That(master.GetHostString(), Is.EqualTo(masters[0]));
                master.SetValue("KEY", "1");
            }
            using (var slave = redisManager.GetReadOnlyClient())
            {
                Assert.That(slave.GetHostString(), Is.EqualTo(slaves[0]));
                Assert.That(slave.GetValue("KEY"), Is.EqualTo("1"));
            }
        }