public void Subscribe(string channelName) { using (var redisClient = new RedisClient(_connection.Url, _connection.Port)) using (_subscription = redisClient.CreateSubscription()) { _subscription.OnSubscribe = channel => { _logging.Info(String.Format("Redis Started Listening On to '{0}'", channel)); }; _subscription.OnUnSubscribe = channel => { _logging.Info(String.Format("Redis UnSubscribed from '{0}'", channel)); redisClient.UnSubscribe(); }; _subscription.OnMessage = (channel, msg) => { _logging.Info(String.Format("Received '{0}' from channel '{1}'", msg, channel)); MessageReceiveEventArgs receivedMsg = new Util.MessageReceiveEventArgs(msg); OnMessageReceivedEventHandler(this, receivedMsg); }; if (OnSubscribeDoneEventHandler != null) { SubscribeDoneEventArgs subscribeDoneEventMsg = new SubscribeDoneEventArgs(true); OnSubscribeDoneEventHandler(this, subscribeDoneEventMsg); } _subscription.SubscribeToChannels(channelName); //blocking } }
/// <summary> /// 订阅 /// </summary> public void Subscribe() { //创建订阅 IRedisSubscription subscription = client.CreateSubscription(); //接受到消息时 subscription.OnMessage += (channel, cmd) => { Console.WriteLine($"接受到消息时:消息通道:{channel},消息内容:{cmd}"); }; //订阅频道时 subscription.OnSubscribe = (channel) => { Console.WriteLine($"订阅客户端:开始订阅消息通道:{channel}"); }; //取消订阅频道时 subscription.OnUnSubscribe = (channel) => { Console.WriteLine($"订阅客户端:取消订阅消息通道:{channel}"); }; //订阅频道 subscription.SubscribeToChannels("channel1", "channel2"); }
/// <summary> /// 订阅 /// </summary> /// <param name="channelList"></param> /// <param name="OnMessage"></param> /// <param name="OnSubscribe"></param> /// <param name="OnUnSubscribe"></param> public void Subscription(List <string> channelList, Action <string, string> OnMessage, Action <string> OnSubscribe = null, Action <string> OnUnSubscribe = null ) { if (channelList == null || !channelList.Any()) { throw new Exception("参数不能为空 或者 列表个数不能为0"); } //创建订阅 IRedisSubscription subscription = Redis.CreateSubscription(); //接受到消息时的委托 subscription.OnMessage = (channel, msg) => { OnMessage(channel, msg); }; //订阅事件处理 subscription.OnSubscribe = channel => { OnSubscribe?.Invoke(channel); }; //取消订阅事件处理 subscription.OnUnSubscribe = channel => { OnUnSubscribe?.Invoke(channel); }; //订阅频道 subscription.SubscribeToChannels(channelList.ToArray()); }
public void Subscription(string channelName, Action <string, string> onMessage, Action <string> OnSubscribe = null, Action <string> OnUnSubscribe = null) { using (IRedisClient Redis = _prcm.GetClient()) { if (_redisSubscription == null) { _redisSubscription = Redis.CreateSubscription(); } //接收消息处理Action if (onMessage != null) { _redisSubscription.OnMessage = onMessage; } if (OnSubscribe != null) { //订阅事件处理 _redisSubscription.OnSubscribe = OnSubscribe; } if (OnUnSubscribe != null) { //取消订阅事件处理 _redisSubscription.OnUnSubscribe = OnUnSubscribe; } //订阅频道 _redisSubscription.SubscribeToChannels(channelName); } }
public void Recive_OPTest() { try { using (var consumer = new RedisClient(ConfigurationManager.AppSettings["RedisClient"], 6379)) { IRedisSubscription subscription = consumer.CreateSubscription(); subscription.OnMessage = (channel, msg) => { BeginInvoke(new Action(() => { listBox1.Items.Add(string.Format("OPTest_Msg:{0}", msg)); })); string stname = "OPTest_Client"; Recive_Client(msg, stname); }; subscription.OnSubscribe = channel => { /* Console.WriteLine("订阅客户端:开始订阅" + channel); */ }; subscription.OnUnSubscribe = a => { /*Console.WriteLine("订阅客户端:取消订阅");*/ }; subscription.SubscribeToChannels(ChannelName + "_OPTest"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void linkLabel39_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Task.Factory.StartNew(() => { using (var consumer = RedisClientManager.GetClient()) { IRedisSubscription subscription = consumer.CreateSubscription(); // 接收到消息 subscription.OnMessage = (channel, message) => { AppendTextAsync("接收到消息:" + ":" + message + " [" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]"); AppendTextAsync(Environment.NewLine); AppendTextAsync(string.Format("频道:{0} 订阅数:{1}", channel, subscription.SubscriptionCount)); AppendTextAsync(Environment.NewLine); AppendTextAsync("------------------------------------------"); AppendTextAsync(Environment.NewLine); }; //订阅事件 subscription.OnSubscribe = channel => AppendTextAsync(string.Format("开始订阅 {0}", channel)); //取消订阅事件 subscription.OnUnSubscribe = channel => AppendTextAsync(string.Format("取消订阅 {0}", channel)); //订阅频道 subscription.SubscribeToChannels("channel_news"); } }); }
private void btnConnect_Click(object sender, EventArgs e) { if (redisClient == null) { redisClient = new RedisClient(txtRedisHost.Text, (int)numRedisPort.Value); redisSubscription = redisClient.CreateSubscription(); redisSubscription.OnMessage = (channel, message) => { if (message == UnsubscribeMessage) { if (unsubscribeSimple) { redisSubscription.UnSubscribeFromChannels(txtUnsubscribeChannelName.Text); unsubscribeSimple = false; } else if (unsubscribeByPattern) { redisSubscription.UnSubscribeFromChannelsMatching(txtUnsubscribeChannelPattern.Text); unsubscribeByPattern = false; } } else { this.BeginInvoke(new Action(() => txtMessages.AppendText(channel + ":" + message + "\r\n"))); } }; } }
static void Main(string[] args) { var conf = new RedisEndpoint() { Host = "xxxxxxxxxxxxxx.redis.cache.windows.net", Password = "******", Ssl = true, Port = 6380 }; using (IRedisClient client = new RedisClient(conf)) { IRedisSubscription sub = null; using (sub = client.CreateSubscription()) { sub.OnMessage += (channel, message) => { try { List <Item> items = JsonConvert.DeserializeObject <List <Item> >(message); Console.WriteLine((string)message); SignalRClass sc = new SignalRClass(); sc.SendRank(items); } catch (Exception ex) { Console.WriteLine(ex.Message); } }; } sub.SubscribeToChannels(new string[] { "Rank" }); } Console.ReadLine(); }
public RedisRegistryProvider() { if (SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration == null) throw new Exception("注册中心配置有误"); string url = SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration.Url; string collectionName = "RegistryData"; var attrs = DictionaryUtils.GetFromConfig(SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration.AddtionalFields); if (attrs != null && attrs.ContainsKey(AttrKeys.Registry_RedisCollectionName) ) { if (!string.IsNullOrEmpty(attrs[AttrKeys.Registry_RedisCollectionName])) { collectionName = attrs[AttrKeys.Registry_RedisCollectionName]; } } _redisClient = new RedisClient(url); _typedClient = _redisClient.As<RegistryDataInfo>(); _table = _typedClient.Lists[collectionName]; _redisSubscription = _redisClient.CreateSubscription(); _redisSubscription.OnMessage += (channel, msg) => { var data = _serializer.Deserialize<ServiceRegistryMetta>(msg); if (this.ServiceChanged == null) return; this.ServiceChanged(this, new ServiceNotifyEventArgs { Data = data }); }; }
public RedisSentinelWorker(RedisSentinel redisSentinel, string host, string masterName) { this.redisSentinel = redisSentinel; this.redisManager = redisSentinel.RedisManager; this.masterName = masterName; //Sentinel Servers doesn't support DB, reset to 0 var sentinelEndpoint = host.ToRedisEndpoint(defaultPort: RedisNativeClient.DefaultPortSentinel); this.sentinelClient = new RedisClient(sentinelEndpoint) { Db = 0 }; this.sentinelPubSubClient = new RedisClient(sentinelEndpoint) { Db = 0 }; this.sentinelSubscription = this.sentinelPubSubClient.CreateSubscription(); this.sentinelSubscription.OnMessage = SentinelMessageReceived; if (Log.IsDebugEnabled) { Log.Debug("Set up Redis Sentinel on {0}".Fmt(host)); } }
static void Main(string[] args) { #region config var conf = new RedisEndpoint() { Host = "******************.redis.cache.windows.net", Password = "******", Ssl = true, Port = 6380 }; #endregion using (IRedisClient client = new RedisClient(conf)) { IRedisSubscription sub = null; using (sub = client.CreateSubscription()) { sub.OnMessage += (channel, message) => { try { List <NotifyData> dataList = Newtonsoft.Json.JsonConvert.DeserializeObject <List <NotifyData> >(message); foreach (NotifyData data in dataList) { //Update Sql UpdateData(data); Console.WriteLine(data.ID + ":" + data.Score); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }; } sub.SubscribeToChannels(new string[] { "SqlSync" }); } Console.ReadLine(); }
public void UnSubscription(string channelName) { using (IRedisClient Redis = _prcm.GetClient()) { _redisSubscription?.UnSubscribeFromAllChannels(); _redisSubscription = null; } }
public void Subscribe(string queueName, Action <byte[]> handler) { this.ExecuteRedisCommandSafety(c => { var s = this.subscription = c.CreateSubscription(); s.OnMessage = (ch, msg) => handler(this.Encoding.GetBytes(msg)); s.SubscribeToChannels(queueName); }); }
private void doSub(object parameter) { IRedisSubscription subClient = redisClient.CreateSubscription(); subClient.OnSubscribe += new Action <string>(onSub); subClient.OnMessage += new Action <string, string>(onOrderMsg); subClient.SubscribeToChannels(channelnames); }
public int Init() { try { string subscribeChannel = ConfigurationSettings.AppSettings["SubscribeChannel"]; string redisIp = ConfigurationSettings.AppSettings["RedisIp"]; int redisPort = int.Parse(ConfigurationSettings.AppSettings["RedisPort"]); Console.WriteLine("MessageManager subscribeChannel:" + subscribeChannel); #region 发布消息 publisher = new RedisClient(redisIp, redisPort); #endregion #region 启动消息分发线程 dispatchThread = new Thread(DispatchThread); dispatchThread.Start(); #endregion #region 订阅消息 //订阅消息 RedisClient redis = new RedisClient(redisIp, redisPort);//redis服务IP和端口 //创建订阅 IRedisSubscription subscription = redis.CreateSubscription(); subscription.OnMessage = (channel, message) => { MessagePack messagePack = new MessagePack(); int len = message.Length; bool result = messagePack.Parse(System.Text.Encoding.UTF8.GetBytes(message)); if (result) { lock (messagePackList) { messagePackList.Add(messagePack); } } }; //订阅频道 subscription.SubscribeToChannels(subscribeChannel); #endregion } catch (Exception e) { Console.WriteLine("MessageManager.Init error:" + e.ToString()); return(-1); } return(0); }
private void btnConnectTest_Click(object sender, EventArgs e) { int intPort = 6379; int.TryParse(txtPort.Text, out intPort); client = new RedisClient(txtIP.Text, intPort, txtPassword.Text); clientV = new RedisClient(txtIP.Text, intPort, txtPassword.Text); subscription = client.CreateSubscription(); }
public TestJobOne(IRedisCacheManager redisCacheManager, IMenuServer menuServer, //IRabbitMQ rabbitMQ, IRedisSubscription redisSubscription) { this._redisCacheManager = redisCacheManager; this._menuServer = menuServer; //this._rabbitMQ = rabbitMQ; this._redisSubscription = redisSubscription; }
/// <summary> /// 監聽某個頻道, 此方法會造成當前執行緒blocking /// </summary> /// <param name="client"></param> /// <param name="channels">要訂閱的頻道</param> /// <param name="onAction">成功訂閱頻道事件</param> /// <param name="msgAction">接收訊息事件</param> /// <param name="endAction">解除訂閱頻道事件</param> public static void SubscribeChannels(this IRedisSubscription subscription, string[] channels, Action <string> onAction, Action <string, string> msgAction, Action <string> endAction) { using (subscription) { subscription.OnSubscribe = onAction; // 當成功訂閱頻道事件 subscription.OnMessage = msgAction; // 訂閱接收訊息事件 subscription.OnUnSubscribe = endAction; // 當解除訂閱頻道事件 subscription.SubscribeToChannels(channels); // 開始訂閱 } }
private void btnDisconnect_Click(object sender, EventArgs e) { if (redisClient != null) { redisClient.Dispose(); redisClient = null; redisSubscription = null; } }
public void StartListen() { using (var redisConsumer = RedisClientsManager.Instance.GetClient()) { _subscription = redisConsumer.CreateSubscription(); _subscription.OnMessage = OnMessage; _subscription.OnSubscribe = OnSubscribe; _subscription.OnUnSubscribe = OnUnSubscribe; _subscription.SubscribeToChannels(ChangedChannel, AddedChannel, DeletedChannel, Heartbeat); } }
protected RedisSubscriber(IRedisClient consumer, IEnumerable <string> channels) { _consumer = consumer; Channels = channels; _subscription = _consumer.CreateSubscription(); _subscription.OnSubscribe = OnSubscribe; _subscription.OnUnSubscribe = OnUnSubscribe; _subscription.OnMessage = OnMessage; }
public RedisSentinelWorker(string host, string sentinelName, PooledRedisClientManager clientsManager = null) { this.sentinelName = sentinelName; this.sentinelClient = new RedisClient(host); this.sentinelPubSubClient = new RedisClient(host); this.sentinelSubscription = this.sentinelPubSubClient.CreateSubscription(); this.sentinelSubscription.OnMessage = SentinelMessageReceived; this.clientsManager = clientsManager; Log.Info("Set up Redis Sentinel on {0}".Fmt(host)); }
public RedisSubscriber(RedisClient redis) { if(redis == null) throw new ArgumentNullException("redis"); _redis = redis; _redisSubscription = new ServiceStack.Redis.RedisSubscription(_redis); _redisSubscription.OnMessage = this.OnReceived; _redisSubscription.OnSubscribe = this.OnSubscribed; _redisSubscription.OnUnSubscribe = this.OnUnsubscribed; }
public RedisSentinelWorker(RedisSentinel redisSentinel, string host, string sentinelName) { this.redisSentinel = redisSentinel; this.redisManager = redisSentinel.redisManager; this.sentinelName = sentinelName; this.sentinelClient = new RedisClient(host); this.sentinelPubSubClient = new RedisClient(host); this.sentinelSubscription = this.sentinelPubSubClient.CreateSubscription(); this.sentinelSubscription.OnMessage = SentinelMessageReceived; Log.Info("Set up Redis Sentinel on {0}".Fmt(host)); }
static void Main(string[] args) { var conf = new RedisEndpoint() { Host = "127.0.0.1", Port = 6379 }; Console.WriteLine("Services Start..."); using (IRedisClient client = new RedisClient(conf)) { IRedisSubscription sub = null; using (sub = client.CreateSubscription()) { sub.OnMessage += (channel, news) => { try { News _news = JsonConvert.DeserializeObject <News>(news); Console.WriteLine(_news.Title); //Güncellenecek 1. Redis Server'ı var conf2 = new RedisEndpoint() { Host = "10.211.55.9", Port = 6379 }; using (IRedisClient clientServer = new RedisClient(conf2)) { clientServer.Set <News>("RedisNews", _news); } //Güncellenecek 2. Redis Server'ı var conf3 = new RedisEndpoint() { Host = "192.168.1.234", Port = 6379 }; using (IRedisClient clientServer2 = new RedisClient(conf3)) { clientServer2.Set <News>("RedisNews", _news); } } catch (Exception ex) { Console.WriteLine("Hata :" + ex.Message); } }; sub.SubscribeToChannels(new string[] { "News" }); } } Console.ReadLine(); }
internal ServiceStackSubscription(RedisClient client) { Trace.WriteLine("ENTER: Constructing {0} ...".FormatInvariant(this.debugName)); this.client = client; this.subscription = this.client.CreateSubscription(); this.subscription.OnMessage = this.OnMessage; this.subscription.OnSubscribe = this.OnSubscribe; this.subscription.OnUnSubscribe = this.OnUnsubscribe; Trace.WriteLine("EXIT: {0} constructed.".FormatInvariant(this.debugName)); }
public void Dispose() { if (this.subscription != null) { this.subscription.UnSubscribeFromAllChannels(); this.subscription.Dispose(); } this.subscription = null; if (this.RedisClient != null) { this.RedisClient.Dispose(); } this.RedisClient = null; }
private static void DemoPublishSubscribe() { using (IRedisClient redisClient = new RedisClient()) { redisClient.PublishMessage("debug", "Published message"); } using (IRedisClient redisClient = new RedisClient()) { IRedisSubscription subscription = redisClient.CreateSubscription(); subscription.OnMessage = (c, m) => Console.WriteLine($"Message from channel {c} = {m}"); // Console waits here subscription.SubscribeToChannels("news"); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); var conf = new RedisEndpoint() { Host = "****.redis.cache.windows.net", Port = 6379, Password = "******" }; Console.WriteLine("Services Start..."); using (IRedisClient client = new RedisClient(conf)) { IRedisSubscription sub = null; using (sub = client.CreateSubscription()) { sub.OnMessage += (channel, exchange) => { try { ExchangeModel _exchange = JsonConvert.DeserializeObject <ExchangeModel>(exchange); Console.WriteLine(_exchange.Name + ": " + _exchange.Value); //Redis UPDATE using (IRedisClient clientServer = new RedisClient(conf)) { string redisKey = "Exchange:" + _exchange.ID; clientServer.Set <ExchangeModel>(redisKey, _exchange); } //Sql UPDATE using (BlackJackContext context = new BlackJackContext()) { var exchangeModel = context.Exchange.FirstOrDefault(ex => ex.Id == _exchange.ID); exchangeModel.Value = (decimal)_exchange.Value; exchangeModel.UpdateDate = DateTime.Now; context.SaveChanges(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }; sub.SubscribeToChannels(new string[] { "Exchange" }); } } }
public void Subscription() { _factory.StartNew(() => { using ( var client = RedisManager.GetRedisClient(string.Format("{0}@{1}:{2}", Setting.Auth, Setting.Host, Setting.Port))) { _subscription = client.CreateSubscription(); _subscription.OnMessage += OnMessage; _subscription.SubscribeToChannels("console"); } }); }
public RedisSentinelWorker(RedisSentinel redisSentinel, string host, string sentinelName) { this.redisSentinel = redisSentinel; this.redisManager = redisSentinel.RedisManager; this.sentinelName = sentinelName; //Sentinel Servers doesn't support DB, reset to 0 this.sentinelClient = new RedisClient(host) { Db = 0 }; this.sentinelPubSubClient = new RedisClient(host) { Db = 0 }; this.sentinelSubscription = this.sentinelPubSubClient.CreateSubscription(); this.sentinelSubscription.OnMessage = SentinelMessageReceived; if (Log.IsDebugEnabled) Log.Debug("Set up Redis Sentinel on {0}".Fmt(host)); }
static void Main(string[] args) { var managerPool = new RedisManagerPool("123.207.159.105:6379"); using (var client = managerPool.GetClient()) { IRedisSubscription subscription = client.CreateSubscription(); subscription.OnMessage = (channel, msg) => { Receive(msg); }; subscription.SubscribeToChannels("OrderItem"); Console.ReadLine(); } }
public RedisSentinelWorker(RedisSentinel redisSentinel, string host, string masterName) { this.redisSentinel = redisSentinel; this.redisManager = redisSentinel.RedisManager; this.masterName = masterName; //Sentinel Servers doesn't support DB, reset to 0 var sentinelEndpoint = host.ToRedisEndpoint(defaultPort:RedisNativeClient.DefaultPortSentinel); this.sentinelClient = new RedisClient(sentinelEndpoint) { Db = 0 }; this.sentinelPubSubClient = new RedisClient(sentinelEndpoint) { Db = 0 }; this.sentinelSubscription = this.sentinelPubSubClient.CreateSubscription(); this.sentinelSubscription.OnMessage = SentinelMessageReceived; if (Log.IsDebugEnabled) Log.Debug("Set up Redis Sentinel on {0}".Fmt(host)); }
static void Subscribe() { ThreadPool.QueueUserWorkItem(x => { using (var client = new RedisClient("localhost", 7071, "iamyourmaster")) { using (_redisSubscription = client.CreateSubscription()) { _redisSubscription.OnMessage += (channel, message) => { SystemMonitorHub.Clients.All.broadCastCpuUsage(message); //_redisSubscription.UnSubscribeFromAllChannels(); }; } _redisSubscription.SubscribeToChannels(new string[] { "system_monitor" }); } }); }
public void Start() { try { if (_thread != null && (_thread.ThreadState == ThreadState.Running || _thread.ThreadState == ThreadState.WaitSleepJoin)) return; Subscription = Client.GetSubscription(); Subscription.OnMessage = (x, y) => { _log.DebugFormat("Message received from [{0}]: {1}", x, y); if (MessageReceived == null) { _log.Debug("No recipients for message."); return; } _log.Debug("Forwarding message."); MessageReceived(y); }; Subscription.OnSubscribe = x => { _log.InfoFormat("Subscribed to [{0}].", x); }; Subscription.OnUnSubscribe = x => { _log.InfoFormat("UnSubscribed from [{0}].", x); }; _thread = new Thread(Run) { Name = "QueueSubscriber_Run" }; _thread.Start(); _log.Info("Started subscriber thread."); _log.DebugFormat("Thread Identifier: {0}", _thread.Name); } catch (Exception exception) { _log.Fatal("Failed to start subscriber thread.", exception); } }
public Subscriber(IRedisSubscription subscription, string channel) { Subscription = subscription; Channel = channel; }