protected Semaphore canClose = new Semaphore(0, 1); // this lock is to prevent closeConnectionThread when there is promise in mapper. If there is no promise in mapper this lock is released and connection is closed public RedisPromiseClient(ConnectionMultiplexer redis) { _redis = redis; _channelSubscription = null; _guid = Guid.NewGuid(); _mapper = new Dictionary <string, Promise>(); }
private async Task EntityEventSubscription(IDataKey key, CancellationToken token, IObserver <ChannelMessage> observer) { ChannelMessageQueue subscriber = null; try { subscriber = await repository.Redis.Multiplexer.SubscribeKeyEvents(key.FullKey).ConfigureAwait(false); do { var result = await subscriber.ReadAsync(token).ConfigureAwait(false); observer.OnNext(result); while (subscriber.TryRead(out result)) { observer.OnNext(result); } } while (!token.IsCancellationRequested); } catch (OperationCanceledException) { } finally { if (subscriber != null) { await subscriber.UnsubscribeAsync().ConfigureAwait(false); } } }
public async Task SubscribeBroadcastMessageEndpoint(Func <MessageWrapper, Task> callback) { async Task consume() { this.queue = await this.redisDatabaseSelector.Connection.GetSubscriber().SubscribeAsync(BROAD_CAST_KEY); while (true && !this.tokenSource.IsCancellationRequested) { try { if (!queue.TryRead(out var item)) { await Task.Delay(TimeSpan.FromMilliseconds(100), this.tokenSource.Token); continue; } var message = this.messageSerializer.Deserialize <MessageWrapper>((byte[])item.Message); await callback.Invoke(message); } catch (Exception e) { this.logger.AddErrorLog(e.Message, e); await Task.Delay(TimeSpan.FromMilliseconds(100), this.tokenSource.Token); } } } this.consume_broadcast_task = Task.Run(consume, this.tokenSource.Token); this.logger.LogInformation("开始订阅广播"); await Task.CompletedTask; }
public EnumerateMessages( ChannelMessageQueue channel, Func <string, T> messageSerializer) { _channel = channel; _messageSerializer = messageSerializer; }
private void Init() { try { var conf = new ConfigurationOptions(); conf.EndPoints.Add(_host, _port); _redis = ConnectionMultiplexer.Connect(conf); _sub = _redis.GetSubscriber().Subscribe("news"); _sub.OnMessage(message => { DownloadMessage(false); }); _dataBase = _redis.GetDatabase(0); Console.WriteLine("Укажите чат:"); _chatKey = ValidatingConsoleInput(); Console.WriteLine("Введите свой ник:"); _userKey = ValidatingConsoleInput(); Console.WriteLine("Добро пожаловать в чат {0}, {1}!", _chatKey, _userKey); DownloadMessage(true); ChattingStart(); } catch (Exception ex) { Console.WriteLine("Error! Message: " + ex.Message); } }
public RedisRoomBackplane(ChatRoom chatRoom, ISubscriber subscriber) { this.subscriber = subscriber; this.chatRoom = chatRoom; this.roomKey = $"chatRoom:messages:{chatRoom.Id}"; this.messageQueue = subscriber.Subscribe(roomKey); }
protected virtual void CloseConnectionThread(object o) { var args = ((ChannelMessageQueue, Semaphore, float, Promise))o; var promiseTimeoutInSeconds = args.Item3; var promise = args.Item4; var l = args.Item2; var c = args.Item1; if (promiseTimeoutInSeconds == -1) { l.WaitOne(); } else { // TODO: this does not work now. It was working for per promise connections l.WaitOne((int)(promiseTimeoutInSeconds * 1000)); promise.TimedOut(); } Console.WriteLine("ALL PROMISES RESOLVED UNSUBSCRIBING..."); c.Unsubscribe(); _channelSubscription = null; canContinue.Release(); }
public static IObservable <T> AsObservable <T>(this ChannelMessageQueue queue) { return(Observable.Create <T>(observer => () => { queue.OnMessage(channelMessage => { observer.OnNext(Deserialize <T>(channelMessage.Message)); }); })); }
public RedisEventStream( IEventDescription eventDescription, ChannelMessageQueue channel, IPayloadSerializer serializer) { _eventDescription = eventDescription; _channel = channel; _serializer = serializer; }
public RedisSubscriber( ISubscriber subscriber, string channel, NotificationEvents nEvents) { _subscriber = subscriber; _channel = channel; _channelMessageQueue = subscriber.Subscribe(channel); _nEvents = nEvents; }
public Consumer(ChannelMessageQueue channelMessageQueue) { _channelMessageQueue = channelMessageQueue; _subject = new Subject <IMessage <T> >(); MessageSource = _subject.AsObservable(); _channelMessageQueue.OnMessage(onMessage); }
public async Task <IEventStream> SubscribeAsync( IEventDescription eventDescription) { ISubscriber subscriber = _connection.GetSubscriber(); ChannelMessageQueue channel = await subscriber .SubscribeAsync(eventDescription.ToString()) .ConfigureAwait(false); return(new RedisEventStream(eventDescription, channel, _serializer)); }
public void Add(Action <RedisChannel, RedisValue> handler, ChannelMessageQueue queue) { if (handler != null) { _handlers += handler; } if (queue != null) { ChannelMessageQueue.Combine(ref _queues, queue); } }
public bool Remove(Action <RedisChannel, RedisValue> handler, ChannelMessageQueue queue) { if (handler != null) { _handlers -= handler; } if (queue != null) { ChannelMessageQueue.Remove(ref _queues, queue); } return(_handlers == null & _queues == null); }
public static async Task Main() { using (var muxer = await ConnectionMultiplexer.ConnectAsync("127.0.0.1")) { var db = muxer.GetDatabase(); var sub = muxer.GetSubscriber(); Console.WriteLine("subscribing"); ChannelMessageQueue queue = await sub.SubscribeAsync("yolo"); Console.WriteLine("subscribed"); } }
public RedisGroup(string groupName, MessagePackSerializerOptions serializerOptions, IGroup inmemoryGroup, ISubscriber redisSubscriber, IDatabaseAsync database) { this.GroupName = groupName; this.serializerOptions = serializerOptions; this.channel = new RedisChannel("MagicOnion.Redis.RedisGroup?groupName=" + groupName, RedisChannel.PatternMode.Literal); this.counterKey = "MagicOnion.Redis.RedisGroup.MemberCount?groupName=" + groupName; this.inmemoryGroup = inmemoryGroup; this.subscriber = redisSubscriber; this.database = database; this.mq = redisSubscriber.Subscribe(channel); mq.OnMessage(message => PublishFromRedisToMemoryGroup(message.Message, this.inmemoryGroup)); }
private void CloseConnectionThread(ChannelMessageQueue channelSubscription, Semaphore luck, float timeoutInSeconds = -1, Promise promise = null) { if (promise == null && timeoutInSeconds != -1) { throw new Exception("if timeout is specified a promise should be passed"); } Thread thread = new Thread(new ParameterizedThreadStart(CloseConnectionThread)); thread.Start((object)(channelSubscription, luck, timeoutInSeconds, promise)); }
public async ValueTask <ISourceStream <TMessage> > SubscribeAsync <TTopic, TMessage>( TTopic topic, CancellationToken cancellationToken = default) where TTopic : notnull { ISubscriber subscriber = _connection.GetSubscriber(); var serializedTopic = topic is string s ? s : _messageSerializer.Serialize(topic); ChannelMessageQueue channel = await subscriber .SubscribeAsync(serializedTopic) .ConfigureAwait(false); return(new RedisEventStream <TMessage>(channel, _messageSerializer)); }
///<summary> ///Функция прослушивания указанного канал на наличие новых сообщений ///</summary> ///<remarks> ///При получении сообщения записывает его, затем когда кол - во сообщений /// = 2, перемножает полученные величины ///</remarks> public static void Listen(IDatabase db, ChannelMessageQueue chanel) { Console.WriteLine("Listening..."); var numbers = new List <string>(); chanel.OnMessage(message => { numbers.Add(db.StringGet(message.Message.ToString())); if (numbers.Count >= 2) { Console.WriteLine("NEW MULTIPLY RESULT: [" + (Int32.Parse(numbers[0]) * Int32.Parse(numbers[1])) + "]"); numbers.Clear(); Console.WriteLine("Listening..."); } }); }
//sequential // sets up a pubsub subscription for this instance. When called many times returns same subscription like a singleton. But unlike singleton it can dispose subscription after no one is using it // hence it should be called before creating any promise otherwise there may not be any thread listening for promise resolving messages. protected virtual void SetupPubSubServer() { lock (mapLock) { if (this._channelSubscription == null) { var channelSubscription = _redis.GetSubscriber().Subscribe(_guid.ToString()); channelSubscription.OnMessage((message) => OnMessageHandler(message.Message)); CloseConnectionThread(channelSubscription, canClose); // this starts thread Thread.Sleep(1000); //give some time to establish subscription _channelSubscription = channelSubscription; return; } } }
/// <summary> /// 订阅消息 /// </summary> /// <param name="topticName"></param> /// <param name="handler"></param> public void SubScribe(string topticName, Action <RedisChannel, RedisValue> handler = null) { ISubscriber subscriber = ConnectionMultiplexer.GetSubscriber(); ChannelMessageQueue channelMessageQueue = subscriber.Subscribe(topticName); channelMessageQueue.OnMessage(channelMessage => { if (handler != null) { string redisChannel = channelMessage.Channel; string msg = channelMessage.Message; handler.Invoke(redisChannel, msg); } else { string msg = channelMessage.Message; Console.WriteLine($"订阅到消息: { msg},Channel={channelMessage.Channel}"); } }); }
public void SubscribeTo(string channelName) { msgQueue = connection.Subscribe(channelName); }
public Subscription(ChannelMessageQueue mq) { this.mq = mq; }
public RedisChannelConsumer(AbstractConsumerSettings consumerSettings, ISubscriber subscriber, IMessageProcessor <byte[]> messageProcessor) { _channelMessageQueue = subscriber.Subscribe(consumerSettings.Topic); _channelMessageQueue.OnMessage(m => messageProcessor.ProcessMessage(m.Message)); }
public RedisSubscription(RedisChannel channel, ChannelMessageQueue messageQueue, CommandFlags flags) { Channel = channel; MessageQueue = messageQueue; Flags = flags; }
public RedisEventStream(ChannelMessageQueue channel, IMessageSerializer messageSerializer) { _channel = channel; _messageSerializer = messageSerializer; }
internal Channel(ChannelMessageQueue channelMessageQueue) { _channelMessageQueue = channelMessageQueue; }
public ChannelMessage(ChannelMessageQueue queue, in RedisChannel channel, in RedisValue value)