private static void ProcessMessage(RedisChannel redisChannel, RedisValue redisValue) { try { var instance = (RedisOutputCachingProvider)Instance(ProviderName) ?? new RedisOutputCachingProvider(); if (redisChannel == KeyPrefix + "Redis.Output.Clear") { var values = redisValue.ToString().Split(':'); int portalId; if (values.Length == 2 && values[0] != InstanceUniqueId && int.TryParse(values[1], out portalId)) // Avoid to clear twice { PurgeCacheInternal(portalId, false); } } else { if (redisValue.ToString().Length > InstanceUniqueId.Length && !redisValue.ToString().StartsWith(InstanceUniqueId)) { int tabId; if (int.TryParse(redisValue.ToString().Substring(InstanceUniqueId.Length + 1), out tabId)) { RemoveInternal(tabId, false); } } } } catch (Exception e) { if (!Shared.ProcessException(ProviderName, e)) { throw; } } }
private void PokemonSubscriptionHandler(RedisChannel channel, RedisValue message) { switch (channel) { case RedisChannels.PokemonAdded: { var pokemon = message.ToString().FromJson <Pokemon>(); if (pokemon != null) { ThreadPool.QueueUserWorkItem(x => InstanceController.Instance.GotPokemon(pokemon)); } break; } case RedisChannels.PokemonUpdated: { var pokemon = message.ToString().FromJson <Pokemon>(); if (pokemon != null) { ThreadPool.QueueUserWorkItem(x => InstanceController.Instance.GotIV(pokemon)); } break; } } }
private TValue Deserialize(RedisValue results) { TValue result; if (typeof(TValue) == typeof(string)) { if (this.m_gzip) { var str = results.ToString(); var bytes = Convert.FromBase64String(str); bytes = Decompress(bytes); result = Encoding.UTF8.GetString(bytes) as TValue; } else { result = results.ToString() as TValue; } } else { var bytes = Convert.FromBase64String(results.ToString()); if (this.m_gzip) { bytes = Decompress(bytes); } result = GetObject(bytes); } return(result); }
private void OnKeyRemove(RedisChannel arg1, RedisValue arg2) { try { Console.WriteLine(arg2.ToString()); var name = arg2.ToString().Split(':'); Console.WriteLine(name.Length); if (name.Length == 3 && name[0] == "reminder" && name[1] == "remove") { var reminderId = long.Parse(name[2]); using var conn = (NpgsqlConnection)_database.GetDbConnection(); conn.QueryAsync(GetReminderById, new { id = reminderId }).ContinueWith((x) => { var cont = x.Result.FirstOrDefault(); if (cont != null) { var userId = (ulong)cont.userId; var reason = (string)cont.reason; _discord.GetUser(userId).GetOrCreateDMChannelAsync().ContinueWith((x) => { var dm = x.Result; dm.SendMessageAsync($"Hay :watch: ! It's time to {reason}").ContinueWith((v) => { conn.Execute(DeleteReminderbyId, new { id = reminderId }); }); }); } }).Wait(); } } catch (Exception e) { Console.WriteLine(e); } }
protected async void imageReceived(RedisChannel channel, RedisValue message) { // InputOnlineFile iof = new InputOnlineFile(); if (_chat_Id.HasValue && message.HasValue) { var imageUrl = _alarmConfig.ImageBaseURL + message.ToString(); try { using (WebClient wc = new WebClient()) { byte[] data = wc.DownloadData(imageUrl); using (MemoryStream ms = new MemoryStream(data)) { InputOnlineFile iof = new InputOnlineFile(ms, message.ToString()); await _botClient.SendPhotoAsync( chatId : _chat_Id.Value, photo : iof); } } } catch (Exception ex) { _logger.LogError(ex, "Error sending photo to Telegram bot."); } } }
static void Main(string[] args) { ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings.Get("redis_connection_string")); ISubscriber subscriber = redis.GetSubscriber(); subscriber.Subscribe("PlayerAddEvents", (channel, message) => { Unblock(); }); RedisKey playerListKey = new RedisKey("PlayerList"); IDatabase database = redis.GetDatabase(); Random random = new Random(DateTime.Now.Second); while (true) { manualResetEvent.Reset(); manualResetEvent.WaitOne(); long playerListLength = database.ListLength(playerListKey); if (playerListLength > 1) { RedisValue player1 = database.ListLeftPop(playerListKey); RedisValue player2 = database.ListLeftPop(playerListKey); string game_topic = random.Next() + "_" + player1.ToString() + player2.ToString() + "_" + random.Next(); database.StringSet(player1.ToString(), "W" + game_topic); database.StringSet(player2.ToString(), "B" + game_topic); } } }
/// <summary> /// 取得快取內容 /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="key">The key of the value to get.</param> /// <returns>The value associated with the specified key.</returns> public T Get <T>(string key) { RedisValue cacheData = this.RedisDb().StringGetAsync(key).Result; try { if (cacheData.IsNullOrEmpty) { return(default(T)); } if (typeof(T) == typeof(string) || !typeof(T).IsClass) { return((T)Convert.ChangeType(cacheData.ToString(), typeof(T))); } return(cacheData.ToString().ToTypedObject <T>()); } catch (Exception exception) { this.Logger.LogError(exception, exception.Message); return(default(T)); } }
public void LoadCommands() { _twitchCommands.Clear(); if (redis.IsConnected("")) { foreach (RedisValue value in redis.SetMembers("commands")) { RedisValue command = redis.HashGet(value.ToString(), "command"); RedisValue message = redis.HashGet(value.ToString(), "message"); RedisValue variable = redis.HashGet(value.ToString(), "variable"); _twitchCommands.Add(command.ToString().ToLower(), new Command { TextCommand = command.ToString(), TextSay = message.ToString(), StoredVariable = variable.ToString() }); } } string path = Path.Join(Directory.GetCurrentDirectory(), "config.json"); string jsonText = File.ReadAllText(path); Config config = JsonConvert.DeserializeObject <Config>(jsonText); config.Commands.ForEach((Command obj) => _twitchCommands.Add(obj.TextCommand.ToLower(), obj)); Console.WriteLine($"Loaded {_twitchCommands.Count} commands"); }
private static void ProcessMessage(RedisChannel redisChannel, RedisValue redisValue) { try { var instance = (RedisCachingProvider)Instance() ?? new RedisCachingProvider(); if (redisChannel == KeyPrefix + "Redis.Clear") { var values = redisValue.ToString().Split(':'); if (values.Length == 3 && values[0] != InstanceUniqueId) // Avoid to clear twice { instance.Clear(values[1], values[2], false); } } else { if (redisValue.ToString().Length > InstanceUniqueId.Length && !redisValue.ToString().StartsWith(InstanceUniqueId)) { instance.Remove(redisValue.ToString().Substring(InstanceUniqueId.Length + 1), false); } } } catch (Exception e) { if (!Shared.ProcessException(ProviderName, e)) { throw; } } }
private void vet_Click(object sender, EventArgs e) { Control c = (Control)sender; string[] menuler = { "menu1", "menu2", "menu2_1", "menu2_2", "menu2_3", "menu3", "menu4", "menu5" }; foreach (string item in menuler) { this.Controls[item + "_Panel"].Visible = false; } menu5_icerik.Controls.Clear(); menu5_1panel.Dock = DockStyle.Fill; menu5_1panel.BringToFront(); menu5_1panel.Visible = true; galeri.Controls.Clear(); resimler.Clear(); galeri.Visible = true; RedisValue rv = bag.HashGet("Vets", c.Tag.ToString()); if (rv.HasValue) { menu5_1panel_klnksahip.Text = rv.ToString().Split(';')[0]; menu5_1panel_klnkad.Text = rv.ToString().Split(';')[1]; menu5_1panel_adres.Text = rv.ToString().Split(';')[2]; menu5_1panel_iletisim.Text = rv.ToString().Split(';')[3]; galeri.Controls.Clear(); resimler.Clear(); galeri.Visible = true; for (int i = 0; i < bag.ListLength("VetImage"); i++) { string[] veri = bag.ListGetByIndex("VetImage", i).ToString().Split(';'); if (veri[0] == c.Tag.ToString()) { pictureBox1.Image = Image.FromStream(new MemoryStream(Convert.FromBase64String(veri[1]))); PictureBox pb = new PictureBox(); pb.Name = "resim_" + i; pb.Image = Image.FromStream(new MemoryStream(Convert.FromBase64String(veri[1]))); pb.SizeMode = PictureBoxSizeMode.Zoom; pb.Size = new Size(galeri.Width - 50, galeri.Width - 50); pb.BorderStyle = BorderStyle.FixedSingle; pb.Cursor = Cursors.Hand; // pb.Click += buyult_Click; if (galeri.Controls.Count > 0) { pb.Location = new Point((galeri.Width / 2) - (pb.Size.Width / 2), galeri.Controls[galeri.Controls.Count - 1].Location.Y + galeri.Width); } else { pb.Location = new Point((galeri.Width / 2) - (pb.Size.Width / 2), 10); } galeri.Controls.Add(pb); } } } }
public static T ToObject <T>(this RedisValue value) where T : class { if (value == RedisValue.Null) { return(null); } return(typeof(T) == typeof(string) ? value.ToString() as T : JsonConvert.DeserializeObject <T>(value.ToString())); }
/// <summary> 反序列化对象 </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> private static object Deserialize(RedisValue value, Type type) { if (!value.HasValue) { return(null); } if (typeof(string) == type) { return(value.ToString()); } return(type.IsSimpleType() ? value.ToString().CastTo(type) : JsonConvert.DeserializeObject(value, type)); }
private static bool ValidateMessage(RedisValue msg) { bool result = false; var msgArray = msg.ToString().Split(':'); if (!msg.IsNullOrEmpty && msg.ToString().ToLower().StartsWith("p") && msgArray.Length == 2) { result = true; } return(result); }
private async void SubscriptionTriggeredResponse(RedisChannel redisChannel, RedisValue redisValue) { try { string channelString = redisChannel.ToString(); if (channelString.Contains("__keyspace@")) { if (redisValue.ToString() == "set") { string key = channelString.Replace("__keyspace@" + DefaultDatabase + "__:", String.Empty); T currentData = await GetByIdCoreAsync(key); CompleteSubscriptionTrigger(currentData); } else if (redisValue.ToString() == "del") { try { string key = redisChannel.ToString().Replace("__keyspace@" + DefaultDatabase + "__:", String.Empty); DeleteCachedEntity(key); } catch { } } } else { T currentData = System.Text.Json.JsonSerializer.Deserialize <T>(redisValue); CompleteSubscriptionTrigger(currentData); } } catch (Exception ex) { try { string key = redisChannel.ToString().Replace("__keyspace@" + DefaultDatabase + "__:", string.Empty); DeleteCachedEntity(key); ex.Data.Add("Key", key); } catch { } RedisRepositoryErrorManager.LogException(this, ex); } }
private void SubscriptionTriggeredResponse(RedisChannel redisChannel, RedisValue redisValue) { try { if (redisValue.ToString() == "set") { string key = redisChannel.ToString().Replace("__keyspace@" + DefaultDatabase + "__:", String.Empty); var currentData = GetByIdCore(key); if (EnableCaching) { if (!SetCachedEntity(currentData)) { if (PreventSubForAlreadyCachedData) { return; } } } if (SubscriptionTriggered == null) { return; } var receivers = SubscriptionTriggered.GetInvocationList(); foreach (SubscriptionTriggeredEventHandler receiver in receivers) { receiver.BeginInvoke(this, currentData, null, null); } } else if (redisValue.ToString() == "del") { try { string key = redisChannel.ToString().Replace("__keyspace@" + DefaultDatabase + "__:", String.Empty); DeleteCachedEntity(key); } catch { } } } catch (Exception ex) { Logger.Log(ex); } }
private User GetUserFromCache(string id) { IDatabase db = _redisResource.GetConnection().GetDatabase(); RedisValue json = db.StringGet($"_users_{id}"); return(JsonSerializer.Deserialize <User>(json.ToString())); }
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; }
private async Task UpdateRelationsRecord(string table, string key, string resourceId) { RedisValue res = await Redis.HashGetAsync(table, key); Resources resources; if (res.HasValue) { resources = Unpack <Resources>(res.ToString()); resources.ResourcesIds.Add(resourceId); } else { resources = new Resources { ResourcesIds = new List <string> { resourceId } }; } var serializedResource = Pack(resources); Tracer.TraceInfo($"Added relation to table <{table}> : {key} - {serializedResource}"); await Redis.HashSetAsync( table, key, serializedResource); }
private void OnTenantChanged(RedisValue value) { if (!value.HasValue || value.IsNullOrEmpty) { return; } var eventArgs = JsonConvert.DeserializeObject <TenantChangedEventArgs>(value.ToString()); if (eventArgs == null) { return; } // Update in memory cache if (this.EnableInMemoryCache) { switch (eventArgs.EventType) { case TenantChangedEventType.TenantUpdated: this.MemoryCache.AddOrUpdate(eventArgs.TenantName, eventArgs.UpdatedTenant, (key, old) => eventArgs.UpdatedTenant); break; case TenantChangedEventType.TenantDeleted: Tenant removed; this.MemoryCache.TryRemove(eventArgs.TenantName, out removed); break; } } // Fire event this.TenantChangedEventHandler?.Invoke(this, eventArgs); }
/// <summary> /// Called when a message about a player is received. /// </summary> /// <param name="Channel">The redis channel.</param> /// <param name="Message">The redis message.</param> private void OnPlayerMessage(RedisChannel Channel, RedisValue Message) { if (Message.IsNullOrEmpty == false) { JObject JSON = JObject.Parse(Message.ToString()); if (JSON.HasValues) { if (JSON["action"].ToObject <string>() == "login") { } else if (JSON["action"].ToObject <string>() == "logout") { } } else { Logging.Error(this.GetType(), "Error, the received message about a player in the channel we subscribed is valid but has no values."); } } else { Logging.Error(this.GetType(), "Error, the received message about a player in the channel we subscribed is either null or empty."); } }
public decimal GetDecimal(string key) { var startTime = DateTimeOffset.UtcNow; var stopwatch = Stopwatch.StartNew(); var retrievedValue = new RedisValue(); try { retrievedValue = Cache.StringGet(key); } catch (TimeoutException timeoutException) { } if (retrievedValue.HasValue == false) { stopwatch.Stop(); return(0); } var format = new NumberFormatInfo { NumberDecimalSeparator = "," }; var value = retrievedValue.ToString().Replace(".", ","); var result = decimal.Parse(value, NumberStyles.AllowDecimalPoint, format); stopwatch.Stop(); return(result); }
public void ListenForMessage(RedisChannel channel, RedisValue value) { Assert.Equal(RedisKey, channel.ToString()); Assert.False(!value.HasValue || value.IsNullOrEmpty); Assert.Equal("INFO test pub/sub message", value.ToString()); ActionRun = true; }
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]); }
public async Task <IActionResult> Query([FromBody] string[] Fields) { string lastReadField = ""; try { string deviceName = $"{Startup.SiteId}.{modbus.GetModbusSystem().DeviceName}"; JObject row = new JObject(); row.Add("deviceId", deviceName); string timeStamp = await redis_ai.HashGetAsync(deviceName, "timestamp"); row.Add("timestamp", timeStamp); if (await redis_ai.KeyExistsAsync(deviceName) == false) { return(NoContent()); } foreach (string field in Fields) { lastReadField = field; if (await redis_ai.HashExistsAsync(deviceName, field)) { RedisValue value = await redis_ai.HashGetAsync(deviceName, field); row.Add(field, value.ToString()); } } return(Ok(row)); } catch { return(NoContent()); } }
public override (List <DataCollection>, List <DataEntity>) GetSchema(DataContainer container) { var collections = new List <DataCollection>(); var entities = new List <DataEntity>(); var redis = ConnectionMultiplexer.Connect(container.ConnectionString); IDatabase db = redis.GetDatabase(); var endpoints = redis.GetEndPoints(); IServer server = redis.GetServer(endpoints.First()); foreach (var key in server.Keys()) { var collectionEntities = new List <DataEntity>(); DataCollection dataCollection = new DataCollection(container, key); dataCollection.Container = container; dataCollection.Name = key; collections.Add(dataCollection); RedisValue value = db.StringGet(key); if (value.HasValue) { var redisdataType = DataType.String.ToString(); entities.Add(new DataEntity(value.ToString(), DataType.String, redisdataType, container, dataCollection)); } } return(collections, entities); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var redis_subscriber = _redis.GetSubscriber(); redis_subscriber.Subscribe("ALARM_TRIGGER", alarmTriggerReceived); redis_subscriber.Subscribe("IMAGE_CAPTURED", imageReceived); redis_subscriber.Subscribe("PERSON_DETECTED", personDetectedReceived); // Initialize the chatID if we already have one RedisValue tmpChatID = _redis_db.StringGet("TELEGRAM_CHAT_ID"); if (!tmpChatID.IsNullOrEmpty) { _chat_Id = long.Parse(tmpChatID.ToString()); } // start botclient _botClient.StartReceiving(); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(1000, stoppingToken); } _botClient.StopReceiving(); }
private void OnInvalidationMessage(RedisChannel pattern, RedisValue data) { if (pattern == Constants.DEFAULT_INVALIDATION_CHANNEL) { this.ProcessInvalidationMessage(data.ToString()); } }
private void insertSubData(RedisValue message) { vw_Call_TelService v = JsonConvert.DeserializeObject <vw_Call_TelService>(message.ToString()); redis.HashSetAsync("order", v.TelServiceCode, message.ToString()); redis.HashDelete("orderlist", v.TelServiceCode); }
public void Test02RetriveJson() { string key = "jsonTest"; TestDO value = new TestDO { Key = key, value1 = 77, value2 = new byte[] { 0x01, 0x02, 0x03 }, value3 = "jsonTest with key 77" }; var db = this.redis.Connection.GetDatabase(); //Try and retrieve from Redis if (!db.KeyExists(key)) { if (db.StringSet(key, value.ToString())) //Add to Redis { logger.Debug($"Success set key:valule => {0}:{1}", key, value); } } RedisValue redisValue = db.StringGet(key); TestDO result = JsonConvert.DeserializeObject <TestDO>(redisValue.ToString()); logger.Debug($"Get key:value => {0}:{1}", key, result); //It's in Redis - return it }
public void Route(RedisChannel channel, RedisValue msg) { try { // get an object from the payload message var payload = JsonSerializer.DeserializeFromString <JsonObject>(msg.ToString()); // get the friendly name of the event (without the namespace) string evnt = payload["event"].Split('\\').Last(); // get the action corresponding to the event var action = _listeners .Where(chan => { return(ParseChannel(chan.Key) == channel.ToString()); }) .DefaultIfEmpty(_catchall.First()) // get the channel .First() .Value .Where(ev => { return(ev.Key == evnt); }) .DefaultIfEmpty(_catchall.First().Value.First()) .First() .Value; // get the listener // trigger the action and pass in the payload action(msg); } catch (Exception e) { Console.WriteLine(e.Message); } }
protected virtual void OnMessageHandler(RedisValue message) { countTime++; lock (mapLock) { var promiseIdActualMessageDto = JsonSerializer.Deserialize <PromiseIdActualMessageDto>(message.ToString()); var promiseId = promiseIdActualMessageDto.PromiseId; var realmsg = promiseIdActualMessageDto.ActualMessage; if (_mapper.ContainsKey(promiseId)) { var promise = _mapper[promiseId]; _mapper.Remove(promiseId); promise.Payload = realmsg; promise._OnResolveBase(); if (_mapper.Count == 0) { canClose.Release(); // to prevent another thread which calls GetPubSubServer to start a subscription while we are closing it, wait until closing thread cleans subscription before releasing mapLock canContinue.WaitOne(); } } } }
public T Get <T>(string key, HttpContext context = null) { var result = default(T); try { var client = CreateInstanceRead(); if (CacheHelpers.IsRequestClearCache(context)) { client.KeyDelete(key); } if (typeof(T) == typeof(string)) { RedisValue redisValue = client.StringGet(key); result = (T)(object)redisValue.ToString(); } else { byte[] redisValue = client.StringGet(key); result = UnZipFromBytes <T>(redisValue); } } catch (Exception ex) { Logger.Error(ex); } return(result); }
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]); } }
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); }
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; } }
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; } } }
/// <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 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")); }
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"]); }
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"]); }
public override string ToString() { if (_params == null) return base.ToString(); var multi = new RedisValue { Type = RedisValueType.MultiBulk, MultiBulkValues = _params }; return multi.ToString(); }
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; } } } }