Exemplo n.º 1
0
 public T Get <T>(string key)
 {
     using (var client = redisManager.GetReadOnlyClient())
     {
         return(client.Get <T>(key));
     }
 }
Exemplo n.º 2
0
 public IEnumerable <string> GetAllUserEmails()
 {
     using (var client = _clientsManager.GetReadOnlyClient())
     {
         var users = client.As <User>();
         return(users.GetAllKeys());
     }
 }
Exemplo n.º 3
0
 public T GetData <T>(string key)
 {
     try
     {
         using (var Redis = RedisClientManager.GetReadOnlyClient())
         {
             return(Redis.Get <T>(key));
         }
     }
     catch (RedisException ex)
     {
         LogManager.GetLogger("ErrorLogger").Error(string.Format("{0}\r\n{1}", ex.Message, ex.StackTrace));
         return(default(T));
     }
 }
        protected override void RunLoop()
        {
            using (var redisClient = clientsManager.GetReadOnlyClient())
            {
                using (var subscription = redisClient.CreateSubscription())
                {
                    subscription.OnUnSubscribe = channel => Log.Debug("OnUnSubscribe: " + channel);

                    subscription.OnMessage = (channel, msg) =>
                    {
                        if (msg == WorkerStatus.StopCommand)
                        {
                            Log.Debug("Stop Command Issued");

                            if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started)
                            {
                                Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping);
                            }

                            Log.Debug("UnSubscribe From All Channels...");
                            subscription.UnSubscribeFromAllChannels(); //Un block thread.
                            return;
                        }

                        this.IncrementMessageCount(1);
                        var messageReceivedArgs = new MessageReceivedArgs {
                            QueueName = msg
                        };
                        this.MqServer.NotifyMessageReceived(messageReceivedArgs);
                    };

                    subscription.SubscribeToChannels(QueueNames.TopicIn); //blocks thread
                }
            }
        }
		private static void UseClientAsync(IRedisClientsManager manager, int clientNo)
		{
			using (var client = manager.GetReadOnlyClient())
			{
				UseClient(client, clientNo);
			}
		}
Exemplo n.º 6
0
 private static void UseClientAsync(IRedisClientsManager manager, int clientNo, string testData)
 {
     using (var client = manager.GetReadOnlyClient())
     {
         UseClient(client, clientNo, testData);
     }
 }
Exemplo n.º 7
0
        private byte[] GetAndRefresh(string key, bool getData)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            Connect();

            byte[][] results = null;

            // This also resets the LRU status as desired.
            // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
            using (var redis = _manager.GetReadOnlyClient() as IRedisNativeClient) {
                if (getData)
                {
                    results = redis.HMGet((_options.InstanceName + key), new [] {
                        AbsoluteExpirationKey.ToUtf8Bytes(),
                        SlidingExpirationKey.ToUtf8Bytes(),
                        DataKey.ToUtf8Bytes()
                    });
                }
                else
                {
                    results = redis.HMGet((_options.InstanceName + key), new [] {
                        AbsoluteExpirationKey.ToUtf8Bytes(),
                        SlidingExpirationKey.ToUtf8Bytes()
                    });
                }
            }

            // TODO: Error handling
            if (results.Length >= 2)
            {
                MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr);
                Refresh(key, absExpr, sldExpr);
            }

            if (results.Length >= 3 && results[2]?.Length > 0)
            {
                return(results[2]);
            }

            return(null);
        }
 public IRedisClient GetReadOnlyClient()
 {
     if (Available)
     {
         return(wrappedClientManager.GetReadOnlyClient());
     }
     else
     {
         throw new SocketException();
     }
 }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
        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);
                }
            }
        }
        private static void UseClient(IRedisClientsManager manager, int clientNo)
        {
            using (var client = manager.GetReadOnlyClient())
            {
                lock (hostCountMap)
                {
                    int hostCount;
                    if (!hostCountMap.TryGetValue(client.Host, out hostCount))
                    {
                        hostCount = 0;
                    }

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

                Log("Client '{0}' is using '{1}'", clientNo, client.Host);
            }
        }
Exemplo n.º 12
0
        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"));
            }
        }
		private static void UseClient(IRedisClientsManager manager, int clientNo)
		{
			using (var client = manager.GetReadOnlyClient())
			{
				lock (hostCountMap)
				{
					int hostCount;
					if (!hostCountMap.TryGetValue(client.Host, out hostCount))
					{
						hostCount = 0;
					}

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

				Log("Client '{0}' is using '{1}'", clientNo, client.Host);
			}
		}
Exemplo n.º 14
0
        public Task <ActivatorParameter> FindParameterAsync(string name, string featureName, string activatorType)
        {
            ActivatorParameter parameter = null;

            using (var client = _clientManager.GetReadOnlyClient())
            {
                var parametersKey = $"xabaril:features:{featureName}:activator:{activatorType}:parameter:{name}";

                var value = client.Get <string>(parametersKey);

                if (value != null)
                {
                    parameter = new ActivatorParameter()
                    {
                        Name          = name,
                        ActivatorType = activatorType,
                        FeatureName   = featureName,
                        Value         = value
                    };
                }
            }

            return(Task.FromResult(parameter));
        }
Exemplo n.º 15
0
        public void Listen()
        {
            Task.Factory.StartNew(() => {
                using (IRedisClient client = _redisClientsManager.GetReadOnlyClient()) {
                    using (IRedisSubscription subscription = client.CreateSubscription()) {
                        subscription.OnMessage = (channel, msg) => {
                            if (msg == "ping" && Ping != null)
                            {
                                Ping(this, EventArgs.Empty);
                            }

                            string[] parts = msg.Split(':');
                            if (parts.Length != 2)
                            {
                                return;
                            }

                            NewError(parts[0], parts[1]);
                        };
                        RetryUtil.Retry(() => subscription.SubscribeToChannels(NotifySignalRAction.NOTIFICATION_CHANNEL_KEY));
                    }
                }
            });
        }
Exemplo n.º 16
0
 public TSaga GetSaga(Guid correlationId)
 {
     using (var client = _clientsManager.GetReadOnlyClient())
         return(client.As <TSaga>().GetById(correlationId));
 }
Exemplo n.º 17
0
 public static ValueTask <IRedisClientAsync> GetReadOnlyClientAsync(this IRedisClientsManager redisManager, CancellationToken token = default)
 {
     return(redisManager is IRedisClientsManagerAsync asyncManager
                         ? asyncManager.GetReadOnlyClientAsync(token)
                         : (redisManager.GetReadOnlyClient() as IRedisClientAsync ?? InvalidAsyncClient <IRedisClientAsync>(redisManager, nameof(redisManager.GetReadOnlyClient))).AsValueTaskResult());
 }
Exemplo n.º 18
0
 protected T Get(string id)
 => (T)Converter.ByteArrayToObject(_redisClientManager.GetReadOnlyClient().Get <byte[]>(AdressString(id)));
        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"));
            }
        }
Exemplo n.º 20
0
        private void RunLoop()
        {
            if (Interlocked.CompareExchange(ref status, WorkerStatus.Started, WorkerStatus.Starting) != WorkerStatus.Starting)
            {
                return;
            }
            Interlocked.Increment(ref timesStarted);

            try
            {
                //RESET
                while (Interlocked.CompareExchange(ref status, 0, 0) == WorkerStatus.Started)
                {
                    using (var redisClient = clientsManager.GetReadOnlyClient())
                    {
                        masterClient = redisClient;

                        //Record that we had a good run...
                        Interlocked.CompareExchange(ref noOfContinuousErrors, 0, noOfContinuousErrors);

                        using (var subscription = redisClient.CreateSubscription())
                        {
                            subscription.OnUnSubscribe = channel => Log.Debug("OnUnSubscribe: " + channel);

                            subscription.OnMessage = (channel, msg) =>
                            {
                                if (msg == WorkerOperation.ControlCommand)
                                {
                                    var op = Interlocked.CompareExchange(ref doOperation, WorkerOperation.NoOp, doOperation);
                                    switch (op)
                                    {
                                    case WorkerOperation.Stop:
                                        Log.Debug("Stop Command Issued");

                                        if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started)
                                        {
                                            Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping);
                                        }

                                        Log.Debug("UnSubscribe From All Channels...");
                                        subscription.UnSubscribeFromAllChannels();     //Un block thread.
                                        return;

                                    case WorkerOperation.Reset:
                                        subscription.UnSubscribeFromAllChannels();     //Un block thread.
                                        return;
                                    }
                                }

                                if (!string.IsNullOrEmpty(msg))
                                {
                                    int[] workerIndexes;
                                    if (queueWorkerIndexMap.TryGetValue(msg, out workerIndexes))
                                    {
                                        foreach (var workerIndex in workerIndexes)
                                        {
                                            workers[workerIndex].NotifyNewMessage();
                                        }
                                    }
                                }
                            };

                            subscription.SubscribeToChannels(QueueNames.TopicIn); //blocks thread
                            masterClient = null;
                        }
                    }
                }

                StopWorkerThreads();
            }
            catch (Exception ex)
            {
                lastExMsg = ex.Message;
                Interlocked.Increment(ref noOfErrors);
                Interlocked.Increment(ref noOfContinuousErrors);

                if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started)
                {
                    Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping);
                }

                StopWorkerThreads();

                if (this.ErrorHandler != null)
                {
                    this.ErrorHandler(ex);
                }


                if (KeepAliveRetryAfterMs != null)
                {
                    Thread.Sleep(KeepAliveRetryAfterMs.Value);
                    Start();
                }
            }
        }
Exemplo n.º 21
0
        private void RunLoop()
        {
            if (Interlocked.CompareExchange(ref status, WorkerStatus.Started, WorkerStatus.Starting) != WorkerStatus.Starting)
            {
                return;
            }
            Interlocked.Increment(ref timesStarted);

            try
            {
                using (var redisClient = clientsManager.GetReadOnlyClient())
                {
                    //Record that we had a good run...
                    Interlocked.CompareExchange(ref noOfContinuousErrors, 0, noOfContinuousErrors);

                    using (var subscription = redisClient.CreateSubscription())
                    {
                        subscription.OnUnSubscribe = channel => Log.Debug("OnUnSubscribe: " + channel);

                        subscription.OnMessage = (channel, msg) => {
                            if (msg == WorkerStatus.StopCommand)
                            {
                                Log.Debug("Stop Command Issued");

                                if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started)
                                {
                                    Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping);
                                }

                                Log.Debug("UnSubscribe From All Channels...");
                                subscription.UnSubscribeFromAllChannels(); //Un block thread.
                                return;
                            }

                            if (!string.IsNullOrEmpty(msg))
                            {
                                int workerIndex;
                                if (queueWorkerIndexMap.TryGetValue(msg, out workerIndex))
                                {
                                    var worker = workers[workerIndex];
                                    worker.NotifyNewMessage();
                                }
                            }
                        };

                        subscription.SubscribeToChannels(QueueNames.TopicIn); //blocks thread
                    }

                    StopWorkerThreads();
                }
            }
            catch (Exception ex)
            {
                lastExMsg = ex.Message;
                Interlocked.Increment(ref noOfErrors);
                Interlocked.Increment(ref noOfContinuousErrors);

                if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started)
                {
                    Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping);
                }

                StopWorkerThreads();

                if (this.ErrorHandler != null)
                {
                    this.ErrorHandler(ex);
                }
            }
        }
Exemplo n.º 22
0
 private IRedisClient GetReadOnlyClient()
 {
     return(!client.IsNull() ? client : clients.GetReadOnlyClient());
 }