Exemplo n.º 1
0
 /// <summary>
 /// Unsubscribe subject.
 /// </summary>
 /// <exception cref="NotImplementedException"></exception>
 public void UnSubscribe()
 {
     if (_connection.State == ConnState.CONNECTED)
     {
         _subscription.Unsubscribe();
     }
 }
Exemplo n.º 2
0
        public void Run()
        {
            _subscription = _connection.SubscribeAsync(Const.RankProcess, "rank_calculator", (sender, args) =>
            {
                var id      = Encoding.UTF8.GetString(args.Message.Data);
                var textKey = Const.TextTitleKey + id;

                if (!_redisStorage.IsKeyExist(textKey))
                {
                    _logger.LogWarning("Text key {textKey} doesn't exists", textKey);
                    return;
                }

                var text    = _redisStorage.Load(textKey);
                var rankKey = Const.RankTitleKey + id;
                var rank    = CalculateRank(text).ToString();

                _redisStorage.Store(rankKey, rank);

                string message = $"Event: RankCalculated, context id: {id}, rank: {rank}";
                _connection.Publish(Const.BrokerRank, Encoding.UTF8.GetBytes(message));
            });

            _subscription.Start();

            Console.WriteLine("Press Enter to exit (RankCalculator)");
            Console.ReadLine();

            _subscription.Unsubscribe();

            _connection.Drain();
            _connection.Close();
        }
 protected override void OnDispose()
 {
     if (_receiver == null)
     {
         return;
     }
     try
     {
         _receiver.Unsubscribe();
         _connection.Close();
     }
     catch
     {
         // ignored
     }
     _receiver = null;
 }
Exemplo n.º 4
0
        public void TestUnsubscribe()
        {
            int count = 0;
            int max   = 20;

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    Boolean unsubscribed = false;
                    asyncSub = s;
                    //s.MessageHandler += UnsubscribeAfterCount;
                    s.MessageHandler += (sender, args) =>
                    {
                        count++;
                        System.Console.WriteLine("Count = {0}", count);
                        if (count == max)
                        {
                            asyncSub.Unsubscribe();
                            lock (mu)
                            {
                                unsubscribed = true;
                                Monitor.Pulse(mu);
                            }
                        }
                    };
                    s.Start();

                    max = 20;
                    for (int i = 0; i < max; i++)
                    {
                        c.Publish("foo", null, null);
                    }
                    Thread.Sleep(100);
                    c.Flush();

                    lock (mu)
                    {
                        if (!unsubscribed)
                        {
                            Monitor.Wait(mu, 5000);
                        }
                    }
                }

                if (count != max)
                {
                    Assert.Fail("Received wrong # of messages after unsubscribe: {0} vs {1}", count, max);
                }
            }
        }
Exemplo n.º 5
0
        public void TestUnsubscribe()
        {
            int count = 0;
            int max   = 20;

            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        Boolean unsubscribed = false;
                        asyncSub = s;
                        //s.MessageHandler += UnsubscribeAfterCount;
                        s.MessageHandler += (sender, args) =>
                        {
                            count++;
                            if (count == max)
                            {
                                asyncSub.Unsubscribe();
                                lock (mu)
                                {
                                    unsubscribed = true;
                                    Monitor.Pulse(mu);
                                }
                            }
                        };
                        s.Start();

                        max = 20;
                        for (int i = 0; i < max; i++)
                        {
                            c.Publish("foo", null, null);
                        }
                        Thread.Sleep(100);
                        c.Flush();

                        lock (mu)
                        {
                            if (!unsubscribed)
                            {
                                Monitor.Wait(mu, 5000);
                            }
                        }
                    }

                    Assert.Equal(max, count);
                }
            }
        }
 public static IObservable <MsgHandlerEventArgs> ToObservable(this IAsyncSubscription sub)
 {
     return(Observable.Create <MsgHandlerEventArgs>(
                observer =>
     {
         EventHandler <MsgHandlerEventArgs> handler = (sender, args) => observer.OnNext(args);
         sub.MessageHandler += handler;
         sub.Start();
         return Disposable.Create(() =>
         {
             sub.MessageHandler -= handler;
             sub.Unsubscribe();
         });
     }));
 }
Exemplo n.º 7
0
        public void Stop()
        {
            _heartbeat.Stop();
            _molDiscoverySubscription.Unsubscribe();
            _molInfoSubscription.Unsubscribe();
            _molTargetedInfoSubscription.Unsubscribe();
            _molRequestSubscription.Unsubscribe();
            _molResponseSubscription.Unsubscribe();
            foreach (IAsyncSubscription subscription in _molRequestServiceSubscriptions)
            {
                subscription.Unsubscribe();
            }

            _conn.Close();
            _logger.LogInformation("NATS Transporter stoped");
        }
        public bool FlushAndUnsubscribe()
        {
            try
            {
                _asyncSubscription?.Unsubscribe();
                _connection?.Drain();
                _connection?.Close();

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error($"An error occured when closing connection. Error: {ex}");

                return(false);
            }
        }
Exemplo n.º 9
0
        public void Dispose()
        {
            try
            {
                messageReceived?.Unsubscribe();
                messageDisconnect?.Unsubscribe();

                // Draining and closing a connection
                c?.Drain();
                // Closing a connection
                c?.Close();

                c = null;
            }
            catch
            {
            }
        }
Exemplo n.º 10
0
        public Task <bool> ReceiveMessageAsync()
        {
            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages of NATS.");
            Console.WriteLine("======================================================");
            // Create a new connection factory to create
            // a connection.
            ConnectionFactory cf = new ConnectionFactory();

            // Creates a live connection to the default
            // NATS Server running locally
            _client = cf.CreateConnection(_connectionString);
            // Setup an event handler to process incoming messages.
            // An anonymous delegate function is used for brevity.
            EventHandler <MsgHandlerEventArgs> h = (sender, args) =>
            {
                // print the message
                //Console.WriteLine(args.Message);
                var messageBody = Encoding.UTF8.GetString(args.Message.Data);
                _saveData.ExecuteQuery(messageBody);
                // Here are some of the accessible properties from
                // the message:
                // args.Message.Data;
                // args.Message.Reply;
                // args.Message.Subject;
                // args.Message.ArrivalSubcription.Subject;
                // args.Message.ArrivalSubcription.QueuedMessageCount;
                // args.Message.ArrivalSubcription.Queue;

                // Unsubscribing from within the delegate function is supported.
                // args.Message.ArrivalSubcription.Unsubscribe();
            };
            // The simple way to create an asynchronous subscriber
            // is to simply pass the event in.  Messages will start
            // arriving immediately.
            IAsyncSubscription s = _client.SubscribeAsync(_queueName, h);

            Console.ReadLine();
            s.Unsubscribe();
            return(Task.FromResult(true));
        }
Exemplo n.º 11
0
        public void Run()
        {
            _subscription = _connection.SubscribeAsync(Const.BrokerRank, (sender, args) =>
            {
                string message = Encoding.UTF8.GetString(args.Message.Data);
                _logger.LogDebug(message);
            });

            _subscription = _connection.SubscribeAsync(Const.BrokerSimilarity, (sender, args) =>
            {
                string message = Encoding.UTF8.GetString(args.Message.Data);
                _logger.LogDebug(message);
            });

            _subscription.Start();

            Console.WriteLine("Press Enter to exit (EventsLogger)");
            Console.ReadLine();

            _subscription.Unsubscribe();

            _connection.Drain();
            _connection.Close();
        }
Exemplo n.º 12
0
        public void TestExtendedReconnectFunctionality()
        {
            Options opts = reconnectOptions;

            Object         msgLock           = new Object();
            AutoResetEvent disconnectedEvent = new AutoResetEvent(false);
            AutoResetEvent reconnectedEvent  = new AutoResetEvent(false);

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                disconnectedEvent.Set();
            };

            opts.ReconnectedEventHandler = (sender, args) =>
            {
                reconnectedEvent.Set();
            };

            byte[]     payload = Encoding.UTF8.GetBytes("bar");
            NATSServer ns      = utils.CreateServerOnPort(22222);

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                IAsyncSubscription s1 = c.SubscribeAsync("foo");
                IAsyncSubscription s2 = c.SubscribeAsync("foobar");

                s1.MessageHandler += incrReceivedMessageHandler;
                s2.MessageHandler += incrReceivedMessageHandler;

                s1.Start();
                s2.Start();

                received = 0;

                c.Publish("foo", payload);
                c.Flush();

                ns.Shutdown();
                // server is stopped here.

                Assert.True(disconnectedEvent.WaitOne(20000));

                // subscribe to bar while connected.
                IAsyncSubscription s3 = c.SubscribeAsync("bar");
                s3.MessageHandler += incrReceivedMessageHandler;
                s3.Start();

                // Unsub foobar while disconnected
                s2.Unsubscribe();

                c.Publish("foo", payload);
                c.Publish("bar", payload);

                // server is restarted here...
                using (NATSServer ts = utils.CreateServerOnPort(22222))
                {
                    // wait for reconnect
                    Assert.True(reconnectedEvent.WaitOne(60000));

                    c.Publish("foobar", payload);
                    c.Publish("foo", payload);

                    using (IAsyncSubscription s4 = c.SubscribeAsync("done"))
                    {
                        AutoResetEvent doneEvent = new AutoResetEvent(false);
                        s4.MessageHandler += (sender, args) =>
                        {
                            doneEvent.Set();
                        };

                        s4.Start();

                        c.Publish("done", payload);
                        Assert.True(doneEvent.WaitOne(4000));
                    }
                } // NATSServer

                Assert.Equal(4, received);
            }
        }
Exemplo n.º 13
0
        public void TestSubDelTaskCountBasic()
        {
            var opts = utils.DefaultTestOptions;

            Assert.Throws <ArgumentOutOfRangeException>(
                () => { opts.SubscriberDeliveryTaskCount = -1; });

            opts.SubscriberDeliveryTaskCount = 2;

            using (new NATSServer())
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    int s1Count = 0;
                    int s2Count = 0;
                    int COUNT   = 10;

                    AutoResetEvent ev1 = new AutoResetEvent(false);
                    AutoResetEvent ev2 = new AutoResetEvent(false);

                    IAsyncSubscription s1 = c.SubscribeAsync("foo", (obj, args) =>
                    {
                        s1Count++;
                        if (s1Count == COUNT)
                        {
                            ev1.Set();
                        }
                    });

                    IAsyncSubscription s2 = c.SubscribeAsync("bar", (obj, args) =>
                    {
                        s2Count++;
                        if (s2Count >= COUNT)
                        {
                            ev2.Set();
                        }
                    });

                    for (int i = 0; i < 10; i++)
                    {
                        c.Publish("foo", null);
                        c.Publish("bar", null);
                    }
                    c.Flush();

                    Assert.True(ev1.WaitOne(10000));
                    Assert.True(ev2.WaitOne(10000));
                    s1.Unsubscribe();

                    Assert.True(s1Count == COUNT);
                    Assert.True(s2Count == COUNT);

                    ev2.Reset();

                    c.Publish("bar", null);
                    c.Flush();

                    Assert.True(ev2.WaitOne(10000));
                    Assert.True(s2Count == COUNT + 1);

                    s2.Unsubscribe();
                }
            }
        }
Exemplo n.º 14
0
        public void TestExtendedReconnectFunctionality()
        {
            Options opts = reconnectOptions;

            Object disconnectedLock = new Object();
            Object msgLock          = new Object();
            Object reconnectedLock  = new Object();

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                System.Console.WriteLine("Disconnected.");
                lock (disconnectedLock)
                {
                    Monitor.Pulse(disconnectedLock);
                }
            };

            opts.ReconnectedEventHandler = (sender, args) =>
            {
                System.Console.WriteLine("Reconnected.");
                lock (reconnectedLock)
                {
                    Monitor.Pulse(reconnectedLock);
                }
            };

            byte[]     payload = Encoding.UTF8.GetBytes("bar");
            NATSServer ns      = utils.CreateServerOnPort(22222);

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                IAsyncSubscription s1 = c.SubscribeAsync("foo");
                IAsyncSubscription s2 = c.SubscribeAsync("foobar");

                s1.MessageHandler += incrReceivedMessageHandler;
                s2.MessageHandler += incrReceivedMessageHandler;

                s1.Start();
                s2.Start();

                received = 0;

                c.Publish("foo", payload);
                c.Flush();

                lock (disconnectedLock)
                {
                    ns.Shutdown();
                    // server is stopped here.

                    Assert.IsTrue(Monitor.Wait(disconnectedLock, 20000));
                }

                // subscribe to bar while connected.
                IAsyncSubscription s3 = c.SubscribeAsync("bar");
                s3.MessageHandler += incrReceivedMessageHandler;
                s3.Start();

                // Unsub foobar while disconnected
                s2.Unsubscribe();

                c.Publish("foo", payload);
                c.Publish("bar", payload);

                // server is restarted here...
                using (NATSServer ts = utils.CreateServerOnPort(22222))
                {
                    // wait for reconnect
                    lock (reconnectedLock)
                    {
                        Assert.IsTrue(Monitor.Wait(reconnectedLock, 60000));
                    }

                    c.Publish("foobar", payload);
                    c.Publish("foo", payload);

                    using (IAsyncSubscription s4 = c.SubscribeAsync("done"))
                    {
                        Object doneLock = new Object();
                        s4.MessageHandler += (sender, args) =>
                        {
                            System.Console.WriteLine("Recieved done message.");
                            lock (doneLock)
                            {
                                Monitor.Pulse(doneLock);
                            }
                        };

                        s4.Start();

                        lock (doneLock)
                        {
                            c.Publish("done", payload);
                            Assert.IsTrue(Monitor.Wait(doneLock, 2000));
                        }
                    }
                } // NATSServer

                if (received != 4)
                {
                    Assert.Fail("Expected 4, received {0}.", received);
                }
            }
        }
Exemplo n.º 15
0
 /// <inheritdoc />
 public void Dispose()
 {
     _subscription?.Unsubscribe();
     _subscription?.Dispose();
     _connection?.Dispose();
 }
Exemplo n.º 16
0
        public void TestUnsubscribe()
        {
            int count = 0;
            int max = 20;

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    Boolean unsubscribed = false;
                    asyncSub = s;
                    //s.MessageHandler += UnsubscribeAfterCount;
                    s.MessageHandler += (sender, args) =>
                    {
                        count++;
                        System.Console.WriteLine("Count = {0}", count);
                        if (count == max)
                        {
                            asyncSub.Unsubscribe();
                            lock (mu)
                            {
                                unsubscribed = true;
                                Monitor.Pulse(mu);
                            }
                        }
                    };
                    s.Start();

                    max = 20;
                    for (int i = 0; i < max; i++)
                    {
                        c.Publish("foo", null, null);
                    }
                    Thread.Sleep(100);
                    c.Flush();

                    lock (mu)
                    {
                        if (!unsubscribed)
                        {
                            Monitor.Wait(mu, 5000);
                        }
                    }
                }

                if (count != max)
                    Assert.Fail("Received wrong # of messages after unsubscribe: {0} vs {1}", count, max);
            }
        }
Exemplo n.º 17
0
 public Task StopAsync(CancellationToken cancellationToken)
 {
     subscription.Unsubscribe();
     connection.Close();
     return(Task.CompletedTask);
 }
Exemplo n.º 18
0
 // it looks like this is the only way to unsubcribe from specific subscription
 // this method might be redundant but keeping it just to have all functionalities
 public void Unsubscribe(IAsyncSubscription subscription)
 {
     subscription.Unsubscribe();
 }