private void OnInstanceNotified(RedisChannel channel,RedisValue notification)
 {
     try
     {
         var list = monitors[channel];
         var notify = BahamutAppInstanceNotification.FromJson(notification);
         switch (notify.NotifyType)
         {
             case BahamutAppInstanceNotification.TYPE_INSTANCE_HEART_BEAT:
                 foreach (var monitor in list) { monitor.OnInstanceHeartBeating(notify); }
                 break;
             case BahamutAppInstanceNotification.TYPE_INSTANCE_OFFLINE:
                 foreach (var monitor in list) { monitor.OnInstanceOffline(notify); }
                 break;
             case BahamutAppInstanceNotification.TYPE_REGIST_APP_INSTANCE:
                 foreach (var monitor in list) { monitor.OnInstanceRegisted(notify); }
                 break;
             default:
                 break;
         }
     }
     catch (Exception)
     {
     }
 }
Example #2
0
        private static void GetMessageUpdates(RedisChannel channel, RedisValue value)
        {
            var vals = value.ToString().Split('|');
            if (vals.Length != 3 || vals[0] == InstanceId) return;

            GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.All.receiveMessage(vals[1], vals[2]);
        }
Example #3
0
 public void ListenForMessage(RedisChannel channel, RedisValue value)
 {
     Assert.AreEqual(RedisKey, channel.ToString());
     Assert.IsFalse(!value.HasValue || value.IsNullOrEmpty);
     Assert.AreEqual("INFO test pub/sub message", value.ToString());
     ActionRun = true;
 }
        void SubscriberMessageReceived(RedisChannel redisChannel, RedisValue value)
        {
            if (!((string)redisChannel).EndsWith("expired")) return;
            var key = Encoding.UTF8.GetString(value);

            LogMethod("Expired", key, null);
            RemoveMethod(key);
        }
Example #5
0
        private void CacheUpdated(RedisChannel channel, RedisValue message)
        {

            var updateNotification = _itemSerializer.Deserialize<CacheUpdateNotificationArgs>(message);

            if (updateNotification.ClientName.Equals(_clientName))
                return;

            if (CacheUpdate != null)
                CacheUpdate(this, updateNotification);
        }
Example #6
0
        private static void GetConnectionUpdates(RedisChannel channel, RedisValue value)
        {
            var vals = value.ToString().Split('|');
            if (vals.Length != 3 || vals[1] == InstanceId) return;

            if (vals[0] == "1")
            {
                GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.All.clientConnected(vals[2]);
            }
            else if (vals[0] == "0")
            {
                GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.All.clientDisconnected(vals[2]);
            }
        }
Example #7
0
        public IDisposable Subscribe(string key, Action<string, string> handler)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            var subscription = new RedisChannel(key, RedisChannel.PatternMode.Literal);

            var subscriber = new RedisSubscriber(() => _subscriber.Value.Unsubscribe(subscription));

            _subscriber.Value.Subscribe(subscription, (k, v) => handler(k, v));

            return subscriber;
        }
        internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternMode mode)
        {
            switch (Type)
            {
                case ResultType.SimpleString:
                case ResultType.BulkString:
                    if (channelPrefix == null)
                    {
                        return new RedisChannel(GetBlob(), mode);
                    }
                    if (AssertStarts(channelPrefix))
                    {
                        var src = (byte[])arr;

                        byte[] copy = new byte[count - channelPrefix.Length];
                        Buffer.BlockCopy(src, offset + channelPrefix.Length, copy, 0, copy.Length);
                        return new RedisChannel(copy, mode);
                    }
                    return default(RedisChannel);
                default:
                    throw new InvalidCastException("Cannot convert to RedisChannel: " + Type);
            }
        }
 internal void Write(RedisChannel channel)
 {
     WriteUnified(outStream, ChannelPrefix, channel.Value);
 }
 public async Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> action)
 {
     await pubsubRedis.GetSubscriber().SubscribeAsync(AddChannelWithPrefix(channel), (c, v) =>
     {
         action(RemoveChannelPrefix(c), v);
     });
 }
Example #11
0
            private void DoSomeThing(RedisChannel channel, RedisValue message)
            {
                DataRow row;
                row = this.Rows.Find(channel.ToString());
                if (row == null)
                {
                    row = this.NewRow();
                    row["ContractCode"] = channel.ToString();
                    try
                    {
                        foreach (String item in ((string)message).Split(','))
                        {
                            String key;
                            String value;
                            String[] keyValue = item.Split(':');
                            key = keyValue[0];
                            value = keyValue[1];
                            if (this.Columns[key].DataType == typeof(String))
                            {
                                row[key] = value;
                            }
                            else if (this.Columns[key].DataType == typeof(decimal))
                            {
                                row[key] = Convert.ToDecimal(value);
                            }
                        }

                        this.Rows.Add(row);


                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Exception");
                    }
                }
                else
                {
                    try
                    {
                        foreach (String item in ((string)message).Split(','))
                        {
                            String key;
                            String value;
                            String[] keyValue = item.Split(':');
                            key = keyValue[0];
                            value = keyValue[1];
                            if (this.Columns[key].DataType == typeof(String))
                            {
                                row[key] = value;
                            }
                            else if (this.Columns[key].DataType == typeof(decimal))
                            {
                                row[key] = Convert.ToDecimal(value);
                            }
                            else if (this.Columns[key].DataType == typeof(DateTime))
                            {
                                row[key] = DateTime.ParseExact(value, "HHmmssfff", CultureInfo.InvariantCulture);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Exception");
                    }
                }
            }
Example #12
0
				private void MasterWasSwitched(RedisChannel redisChannel, RedisValue redisValue)
        {
	        _connection.ConnectionFailed -= OnConnectionFailed;
	        _connection.ConnectionRestored -= OnConnectionRestored;
	        _connection.ErrorMessage -= OnError;
          _connection.Close();
          if (redisValue.IsNullOrEmpty) return;
          var message = redisValue.ToString();
          var messageParts = message.Split(' ');
          var ip = IPAddress.Parse(messageParts[3]);
          var port = int.Parse(messageParts[4]);
          EndPoint newMasterEndpoint = new IPEndPoint(ip, port);
          if (_options.EndPoints.Any() && newMasterEndpoint == _options.EndPoints[0]) return;
          _options.EndPoints.Clear();
          _options.EndPoints.Add(newMasterEndpoint);

          _connection = ConnectionMultiplexer.Connect(_options);
          _connection.ConnectionFailed += OnConnectionFailed;
          _connection.ConnectionRestored += OnConnectionRestored;
          _connection.ErrorMessage += OnError;
          _redisSubscriber = _connection.GetSubscriber();
          var handler = ConnectionRestored;
          if (handler != null) handler(new ApplicationException("Redis master was switched"));
        }
 public PubSubReceiver(RedisConfiguration config, string channelName, TraceWriter trace)
 {
     _config = config;
     _channel = new RedisChannel(channelName, RedisChannel.PatternMode.Auto);
     _trace = trace;
 }
Example #14
0
        private void onReceiveMessage(RedisChannel channel, RedisValue value)
        {
            string work = (string)database.ListRightPop($"{(string)channel}-bl");
            if (work == null)
            {
            //                Console.WriteLine($"{channel} got thing, but no message");
                return;
            }
            #if log
            Console.WriteLine("Receiving Message: " + channel + "    " + work);
            Console.WriteLine();
            #endif

            RedisMessage message = JsonConvert.DeserializeObject<RedisMessage>(work, new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Objects
            });

            if (lateTaskManager.Exists(message.Guid))
            {
                lateTaskManager.Resolve(message.Guid,message);
            }
            else
            {
                if (subscriptions[channel] != null)
                {
                    subscriptions[channel](message);
                }
            }
        }
        /// <summary>
        /// Handlers the specified redis channel.
        /// </summary>
        /// <param name="redisChannel">The redis channel.</param>
        /// <param name="redisValue">The redis value.</param>
        private void Handler(RedisChannel redisChannel, RedisValue redisValue)
        {
            if (!redisValue.HasValue || _messageId.Id.Value.ToString() != redisValue.ToString())
            {
                return;
            }

            _waitHandle.Set();
        }
 private void OnInvalidationMessage(RedisChannel pattern, RedisValue data)
 {
     if (pattern == Constants.DEFAULT_INVALIDATION_CHANNEL)
     {
         this.ProcessInvalidationMessage(data.ToString());
     }
 }
        private void onMessage(RedisChannel channel, RedisValue value)
        {
            log(Logging.LoggingLevel.Detailed, "Received Message: {0}", value.ToString());

            var dict = value.ToString().ToObject<Dictionary<string, string>>();
            if (OnMessage != null)
                OnMessage(dict["cacheName"], dict["message"]);
        }
Example #18
0
 private void ProcessRedisCacheInstruction(RedisChannel channel, RedisValue message )
 {
     string[] messageParts = message.ToString().Split( ',' );
     if (messageParts.Length > 0 )
     {
         var action = messageParts[0];
         switch ( action )
         {
             case "REMOVE":
                 {
                     if (messageParts.Length > 1 )
                     {
                         RemoveFromMemoryCache( messageParts[1] );
                     }
                     break;
                 }
             case "FLUSH":
                 {
                     FlushMemoryCache();
                     break;
                 }
             case "REFRESH_AUTH_ENTITY":
                 {
                     if ( messageParts.Length > 2 )
                     {
                         Rock.Security.Authorization.RefreshEntity( messageParts[1].AsInteger(), messageParts[2].AsInteger() );
                     }
                     break;
                 }
             case "REFRESH_AUTH_ACTION":
                 {
                     if ( messageParts.Length > 3 )
                     {
                         Rock.Security.Authorization.RefreshAction( messageParts[1].AsInteger(), messageParts[2].AsInteger(), messageParts[3] );
                     }
                     break;
                 }
             case "FLUSH_AUTH":
                 {
                     Rock.Security.Authorization.FlushAuth();
                     break;
                 }
             case "REMOVE_ENTITY_ATTRIBUTES":
                 {
                     Rock.Web.Cache.AttributeCache.RemoveEntityAttributes();
                     break;
                 }
             case "PING":
                 {
                     var response = string.Format( "PONG: From {0}: {1}", System.Environment.MachineName, System.AppDomain.CurrentDomain.FriendlyName );
                     SendRedisCommand( response );
                     break;
                 }
         }
     }
 }
Example #19
0
 private void HandleMessage(RedisChannel channel, RedisValue key)
 {
     this.TryDequeueCommand();
 }
Example #20
0
 private void OnNotificationReceived(RedisChannel redisChannel, RedisValue redisValue)
 {
     _logger.Debug("Redis notification received in receiver for {RedisKey}", _redisKey);
     _receiveSemaphore.Release();
 }
        private void onExpireItemCache(RedisChannel channel, RedisValue value)
        {
            log(Logging.LoggingLevel.Detailed, "Received Expire Item: {0}", value.ToJson());

            var dict = value.ToString().ToObject<Dictionary<string, string>>();
            if (OnExpireItem != null)
                OnExpireItem(dict["cacheName"], dict["key"], dict["itemKey"]);
        }
Example #22
0
 private void ChannelPulse(RedisChannel redisChannel, RedisValue redisValue)
 {
     lock (this.acquireLock)
     {
         this.wasPulsed = true;
         Monitor.Pulse(this.acquireLock);
     }
 }
 private void OnKeySpaceNotificationMessage(RedisChannel pattern, RedisValue data)
 {
     var prefix = pattern.ToString().Substring(0, 10);
     switch (prefix)
     {
         case "__keyevent":
             this.ProcessInvalidationMessage(data.ToString());
             break;
         default:
             //nop
             break;
     }
 }
Example #24
0
        private void WaitChannelPulse(RedisChannel redisChannel, RedisValue redisValue)
        {
            lock (this.waitLock)
            {
                if (this.wasWaitPulsed)
                {
                    // somehow we got message that we shouldn't get
                    return;
                }

                try
                {
                    this.wasWaitPulsed = true;
                    var pulseType = (PulseType)(int.Parse(redisValue.ToString()));
                    if (pulseType == PulseType.One)
                    {
                        // try get permission to wake
                        try
                        {
                            this.redisStorage.Remove(this.PulseFile);
                        }
                        catch (StorageKeyDoesntExistException)
                        {
                            // failed - need to sleep longer
                            return;
                        }
                    }

                    // unsubscribe yourself
                    this.redisStorage.Unsubscribe(this.WaitChannel, this.WaitChannelPulse);
                    Monitor.Pulse(this.waitLock);
                }
                finally
                {
                    this.wasWaitPulsed = false;
                }
            }
        }
 public MessageCompletable(RedisChannel channel, RedisValue message, Action<RedisChannel, RedisValue> handler)
 {
     this.channel = channel;
     this.message = message;
     this.handler = handler;
 }
        private void MasterWasSwitched(RedisChannel redisChannel, RedisValue redisValue)
        {
            if (redisValue.IsNullOrEmpty) return;
              var message = redisValue.ToString();
              var messageParts = message.Split(' ');
              var ip = IPAddress.Parse(messageParts[3]);
              var port = int.Parse(messageParts[4]);
              EndPoint newMasterEndpoint = new IPEndPoint(ip, port);
              if (_configOption.EndPoints.Any() && newMasterEndpoint == _configOption.EndPoints[0]) return;
              _configOption.EndPoints.Clear();
              _configOption.EndPoints.Add(newMasterEndpoint);

              _redisMultiplexer = LogUtility.logger == null
            ? ConnectionMultiplexer.Connect(_configOption)
            : ConnectionMultiplexer.Connect(_configOption, LogUtility.logger);

              _connection = _redisMultiplexer.GetDatabase(_configuration.DatabaseId);
        }