static void DeviceListen(object param) { string deviceName = param.ToString(); StackExchange.Redis.ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"); ISubscriber sub = redis.GetSubscriber(); if (redis.IsConnected) { Console.WriteLine("Subscribe " + deviceName.Trim()); sub.Subscribe(deviceName.Trim(), (channel, bytes) => { using (var memoryStream = new MemoryStream(bytes)) { var client = ProtoBuf.Serializer.Deserialize <Common.Models.Client>(memoryStream); Console.WriteLine(client.DeviceName); //chengdu_pov.mqtt.iot.gz.baidubce.com lock (GlobalVariable.PovDevices[client.DeviceName.Trim()]) { GlobalVariable.PovDevices[client.DeviceName].ClientMisstion.Enqueue(client); Console.WriteLine("Device {0} ,enqueue ,at {1}", client.DeviceName, DateTime.Now.ToLongTimeString()); } } //Console.WriteLine((string)bytes); }); } }
public JsonResult Post(string dataJson) { string msg = string.Empty; bool state = true; try { var client = Serializer.ToObject <Client>(dataJson); ClientService dbService = new ClientService(); client.Id = dbService.AddClient(client); ISubscriber redisPublic = redis.GetSubscriber(); if (redis.IsConnected) { using (var memoryStream = new MemoryStream()) { ProtoBuf.Serializer.Serialize <Client>(memoryStream, client); redisPublic.Publish(client.DeviceName.Trim(), memoryStream.ToArray()); } } return(new JsonResult { Data = new { state = state, msg = msg } }); } catch (Exception e) { return(new JsonResult { Data = new { state = state, msg = e.Message } }); } }
internal WorkflowManagement(ConnectionMultiplexer mux, ITaskHandler taskHandler, WorkflowHandler workflowHandler, string identifier, IEnumerable<string> typesProcessed, ILua lua, EventHandler<Exception> exceptionHandler = null, Behaviours behaviours = Behaviours.All) { _taskHandler = taskHandler; _workflowHandler = workflowHandler; if (exceptionHandler != null) { ExceptionThrown += exceptionHandler; } _typesProcessed = typesProcessed; _db = mux.GetDatabase(); _sub = mux.GetSubscriber(); if (_typesProcessed == null || _typesProcessed.Count() == 0) { _sub.Subscribe("submittedTask", (c, v) => { ProcessNextTask(); }); } else { foreach(var t in _typesProcessed) { _sub.Subscribe("submittedTask:" + t, (c, v) => { ProcessNextTask(t); }); } } _sub.Subscribe("workflowFailed", (c, v) => { ProcessNextFailedWorkflow(); }); _sub.Subscribe("workflowComplete", (c, v) => { ProcessNextCompleteWorkflow(); }); _lua = lua; _lua.LoadScripts(_db, mux.GetServer("localhost:6379")); _identifier = identifier; if (behaviours.HasFlag(Behaviours.AutoRestart)) { var resubmittedTasks = ResubmitTasks(); foreach (var item in resubmittedTasks) { Console.WriteLine("Resubmitted {0}", item); } } }
static string subscribeSelfFilter(ConnectionMultiplexer redis, string SubscribeItem, int timeOut, Func<RedisValue, bool> filter) { AutoResetEvent autoEvent = new AutoResetEvent(false); var sub = redis.GetSubscriber(); Console.WriteLine("client is waitting"); var res = string.Empty; var t = Thread.CurrentThread; var flag = true; var tt2 = DateTime.MinValue.Ticks; var tt1 = DateTime.MaxValue.Ticks; //Task realT = null; sub.SubscribeAsync(SubscribeItem, (channel, message) => { if (flag && filter(message)) { //sub.Unsubscribe(SubscribeItem); Console.WriteLine(message); res = message.ToString(); //res = "evil"; autoEvent.Set(); } tt2 = DateTime.Now.Ticks; Console.WriteLine("processTime:" + (tt2 - tt1)); }); //flag = false; Console.WriteLine("timeout"); autoEvent.WaitOne(1); //Thread.Sleep(timeOut); tt1 = DateTime.Now.Ticks; //sub.Publish(SubscribeItem, "aa"); sub.UnsubscribeAllAsyncBefore().Wait(); Console.WriteLine("res:" + res); var tt3 = DateTime.Now.Ticks; Console.WriteLine("pubTime:" + (tt3 - tt1)); //Thread.Sleep(500); //redis.Close(false); //if(realT != null) //{ // realT.Wait(); //} //sub.Unsubscribe(SubscribeItem); return res; }
public async Task ConnectAsync(string connectionString, TraceSource trace) { _connection = await ConnectToRedis(connectionString); _connection.ConnectionFailed += OnConnectionFailed; _connection.ConnectionRestored += OnConnectionRestored; _connection.ErrorMessage += OnError; _trace = trace; _redisSubscriber = _connection.GetSubscriber(); }
public async Task ConnectAsync(string connectionString, ILogger logger) { _connection = await ConnectionMultiplexer.ConnectAsync(connectionString); _connection.ConnectionFailed += OnConnectionFailed; _connection.ConnectionRestored += OnConnectionRestored; _connection.ErrorMessage += OnError; _logger = logger; _redisSubscriber = _connection.GetSubscriber(); }
public RedisStorage(ConfigurationOptions Options, int db, string prefix) { if (Options == null) throw new ArgumentNullException("Options"); var HangfireOptions = new RedisStorageOptions() { Prefix = prefix }; Db = db; Options.AbortOnConnectFail = false; Options.ClientName = ClientName; ServerPool = ConnectionMultiplexer.Connect(Options); var Sub = new RedisSubscribe(ServerPool.GetSubscriber(), prefix); var LockID = Guid.NewGuid().ToString(); StorageInternals = new RedisStorageInternals(prefix, LockID, Sub); FetchedJobsOptions = new FetchedJobsWatcherOptions(HangfireOptions); }
public bool Initialize(string clientId, string connection) { var connectionDict = connection.ToObject<Dictionary<string, object>>(); ClientId = clientId; var server = connectionDict.GetSetting("server", ""); _multiplexer = ConnectionMultiplexer.Connect(server); var subscriber = _multiplexer.GetSubscriber(); subscriber.Subscribe("RedisNotifier.serverMessage", onMessage); subscriber.Subscribe("RedisNotifier.expireCache", onExpireCache); subscriber.Subscribe("RedisNotifier.expireItemCache", onExpireItemCache); BroadcastMessage(string.Format("Redis {0} client connected on: {1}", clientId, server)); log(Logging.LoggingLevel.Minimal, "Initialized"); return true; }
public RedisHybridCacheClient(ConnectionMultiplexer connectionMultiplexer, ISerializer serializer = null, ILoggerFactory loggerFactory = null) : base(new RedisCacheClient(connectionMultiplexer, serializer, loggerFactory), new RedisMessageBus(connectionMultiplexer.GetSubscriber(), "cache-messages", serializer, loggerFactory), loggerFactory) { }
private void makeEvent(StackExchange.Redis.ConnectionMultiplexer redis, String id, String value) { ISubscriber sub = redis.GetSubscriber(); sub.Publish("events", id); }
/// <summary> /// Initializes a new instance of the <see cref="RockMemoryCache"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="config">The configuration.</param> private RockMemoryCache( string name, NameValueCollection config = null ) : base(name, config) { // Use lambda expressions to create a set method for MemoryCache._stats._lastTrimGen2Count to circumvent poor functionality of MemoryCache // The default MemoryCache does not check for memory pressure except after a Gen 2 Garbage Collection. We want to do this more often than that. // So this method allows us to reset the field the MemoryCacheStatistics object uses periodically to a new value, to force the trim to be checked. // Define the types var memoryCacheType = typeof( MemoryCache ); var memoryCacheStatisticsType = memoryCacheType.Assembly.GetType( "System.Runtime.Caching.MemoryCacheStatistics", true ); // Define the _stats field on MemoryCache var statsField = memoryCacheType.GetField( "_stats", BindingFlags.Instance | BindingFlags.NonPublic ); // Define the _lastTrimGen2Count field on MemoryCacheStatistics var lastTrimGen2CountField = memoryCacheStatisticsType.GetField( "_lastTrimGen2Count", BindingFlags.Instance | BindingFlags.NonPublic ); // Get a reference to this memory cache instance var targetExpression = Expression.Constant( this, typeof( MemoryCache ) ); // Define the parameters to the method var valueExpression = Expression.Parameter( typeof( int ), "value" ); // Create the field expressions var statsFieldExpression = Expression.Field( targetExpression, statsField ); var lastTrimGen2CountFieldExpression = Expression.Field( statsFieldExpression, lastTrimGen2CountField ); // Create the field value assignment expression var fieldValueAssignmentExpression = Expression.Assign( lastTrimGen2CountFieldExpression, valueExpression ); // Compile to function _setMemoryCacheLastTrimGen2CountFunc = Expression.Lambda<Action<int>>( fieldValueAssignmentExpression, valueExpression ).Compile(); // Fire this method initially after a 1000 ms delay _setMemoryCacheLastTrimGen2CountTimer = new Timer( SetMemoryCacheLastTrimGen2Count, null, 1000, Timeout.Infinite ); // Check to see if caching has been disabled _isCachingDisabled = ConfigurationManager.AppSettings["DisableCaching"].AsBoolean(); // setup redis cache clustering if needed _isRedisClusterEnabled = ConfigurationManager.AppSettings["EnableRedisCacheCluster"].AsBoolean(); if ( _isRedisClusterEnabled && _isCachingDisabled == false ) { string connectionString = ConfigurationManager.AppSettings["RedisConnectionString"]; if ( !string.IsNullOrWhiteSpace( connectionString ) ) { try { _redisConnection = ConnectionMultiplexer.Connect( connectionString ); _redisConnection.PreserveAsyncOrder = false; // enable concurrent processing of pub/sub messages https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/PubSubOrder.md _redisConnection.ConnectionRestored += _redisConnection_ConnectionRestored; _redisConnection.ConnectionFailed += _redisConnection_ConnectionFailed; _isRedisConnected = true; } catch ( Exception ex ) { Model.ExceptionLogService.LogException( ex, null ); } if ( _redisConnection != null ) { // setup the subscription to listen for published instructions on caching ISubscriber sub = _redisConnection.GetSubscriber(); sub.Subscribe( REDIS_CHANNEL_NAME, ( channel, message ) => { ProcessRedisCacheInstruction( channel, message ); } ); } else { _isRedisClusterEnabled = false; } } else { _isRedisClusterEnabled = false; } } }
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 ConnectToSentinel() { _sentinelConnection = ConnectionMultiplexer.Connect(_sentinelConfiguration); var subscriber = _sentinelConnection.GetSubscriber(); subscriber.Subscribe("+switch-master", MasterWasSwitched); _sentinelConnection.ConnectionFailed += SentinelConnectionFailed; _sentinelConnection.ConnectionRestored += SentinelConnectionRestored; }
public RedisStorage(ConfigurationOptions RedisOptions, RedisStorageOptions HangfireOptions) { if (RedisOptions == null) throw new ArgumentNullException("RedisOptions"); if (HangfireOptions == null) throw new ArgumentNullException("HangfireOptions"); Db = HangfireOptions.Db; RedisOptions.AbortOnConnectFail = false; RedisOptions.ClientName = ClientName; ServerPool = ConnectionMultiplexer.Connect(RedisOptions); var Sub = new RedisSubscribe(ServerPool.GetSubscriber(), HangfireOptions.Prefix); var LockID = Guid.NewGuid().ToString(); StorageInternals = new RedisStorageInternals(HangfireOptions.Prefix, LockID, Sub); FetchedJobsOptions = new FetchedJobsWatcherOptions(HangfireOptions); }
private void CreateEvent(StackExchange.Redis.ConnectionMultiplexer redis, String id, string events, String value = null) { ISubscriber sub = redis.GetSubscriber(); sub.Publish(events, id); }
private static ISubscriber CreateSubscriber(string connectionString) { _connection = ConnectionMultiplexer.Connect(connectionString); var subscriber = _connection.GetSubscriber(); return subscriber; }