Exemple #1
0
 // Convenience method to create a queue or standard subscriber
 private IStanSubscription CreateSubscriber(IStanConnection c, EventHandler <StanMsgHandlerArgs> msgHandler)
 {
     if (qGroup != null)
     {
         return(c.Subscribe(subject, qGroup, sOpts, msgHandler));
     }
     return(c.Subscribe(subject, sOpts, msgHandler));
 }
Exemple #2
0
        public void Start()
        {
            // connect to STAN
            var cf          = new StanConnectionFactory();
            var natsOptions = StanOptions.GetDefaultOptions();

            natsOptions.NatsURL = "nats://localhost:4223";
            _stanConnection     = cf.CreateConnection("test-cluster", "ShippingService", natsOptions);

            // create events subscription
            StanSubscriptionOptions stanOptions = StanSubscriptionOptions.GetDefaultOptions();

            stanOptions.DurableName = "ShippingService";

            // determine where to start reading in the event-stream
            ulong?lastSeqNr = GetLastSequenceNumber();

            if (lastSeqNr != null)
            {
                lastSeqNr++;
                stanOptions.StartAt(lastSeqNr.Value);

                Console.WriteLine($"Replaying from seq# {lastSeqNr}");
            }
            else
            {
                stanOptions.DeliverAllAvailable();

                Console.WriteLine("Replaying all messages.");
            }

            _stanConnection.Subscribe("store.events", stanOptions, EventReceived);
        }
Exemple #3
0
        static void TestSTAN(IStanConnection conn)
        {
            Task.Run(async() =>
            {
                var i = 0;
                while (true)
                {
                    try
                    {
                        string guid = conn.Publish("stest", UTF8Encoding.UTF8.GetBytes(i.ToString()), null);

                        await Task.Delay(1000);
                        i++;
                    }
                    catch (Exception err)
                    {
                        Console.WriteLine(err);
                    }
                }
            });

            var sOpts = StanSubscriptionOptions.GetDefaultOptions();

            sOpts.AckWait = 60000;
            var s = conn.Subscribe("stest", sOpts, (obj, msgArs) =>
            {
                Console.WriteLine(UTF8Encoding.UTF8.GetString(msgArs.Message.Data));
            });
        }
Exemple #4
0
        public async Task StartAsync(string consumerId)
        {
            StanOptions options = StanOptions.GetDefaultOptions();

            options.NatsURL = _natsOptions.Url;

            var stanSubOptions = StanSubscriptionOptions.GetDefaultOptions();

            stanSubOptions.DurableName = _natsOptions.DurableName;

            _stanConnection = new StanConnectionFactory()
                              .CreateConnection(_natsOptions.ClusterId, consumerId, options);

            try
            {
                _stanConnection
                .Subscribe(_natsOptions.Subject, stanSubOptions, (obj, args) =>
                {
                    string messageData = Encoding.UTF8.GetString(args.Message.Data);
                    Console.WriteLine($"[#{args.Message.Sequence}] {messageData}");

                    var message    = JsonSerializer.Deserialize <Message>(messageData);
                    message.Number = args.Message.Sequence;
                    _messageRepository.AddAsync(message).GetAwaiter().GetResult();
                });
            }
            catch (Exception e)
            {
                _logger.LogError($"Ошибка подписки на сообщения: {e.ToString()}");
                CloseConnection();
            }

            await Task.CompletedTask;
        }
Exemple #5
0
        public void Subscriber(string subject, EventHandler <StanMsgHandlerArgs> handler, bool in_all = false, bool is_last = false, ulong since_seq_no = 0, DateTime?since_duration = null)
        {
            if (conn == null || conn.NATSConnection.State != ConnState.CONNECTED)
            {
                return;
            }
            StanSubscriptionOptions sOpts = StanSubscriptionOptions.GetDefaultOptions();

            if (in_all)
            {
                sOpts.DeliverAllAvailable();
            }
            else if (is_last)
            {
                sOpts.StartWithLastReceived();
            }
            else if (since_seq_no != 0)
            {
                sOpts.StartAt(since_seq_no);
            }
            else if (since_duration.HasValue)
            {
                sOpts.StartAt(since_duration.Value);
            }
            subject = $"{producID}_{subject}";
            dicSubscription.GetOrAdd(subject, conn.Subscribe(subject, sOpts, handler));
        }
                internal void ProcessMsgs(string url, string clusterID)
                {
                    IStanConnection sc = null;

                    try
                    {
                        sc = CreateConnection(url, clusterID, "synadia-rel-sub");

                        var opts = StanSubscriptionOptions.GetDefaultOptions();
                        opts.AckWait     = 60000;
                        opts.ManualAcks  = true;
                        opts.MaxInflight = 32;
                        opts.DurableName = "synadia-restest";

                        sc.Subscribe("synadia.restest", "qg", opts, ProcessMsg);

                        FeV.WaitOne();
                    }
                    catch (Exception e)
                    {
                        Log("Create Subscriber failed: " + e);
                    }
                    finally
                    {
                        sc?.Close();
                    }

                    Log("Subscriber is finished.");
                }
Exemple #7
0
        private TimeSpan ReceiveAsyncSubscriber(IStanConnection c)
        {
            var sw = new Stopwatch();
            var ev = new AutoResetEvent(false);

            EventHandler <StanMsgHandlerArgs> msgHandler = (sender, args) =>
            {
                if (_received == 0)
                {
                    sw.Start();
                }

                _received++;

                if (Verbose)
                {
                    Console.WriteLine("Received seq # {0}: {1}",
                                      args.Message.Sequence,
                                      System.Text.Encoding.UTF8.GetString(args.Message.Data));
                }

                if (_received >= Count)
                {
                    sw.Stop();
                    ev.Set();
                }
            };

            using (var s = c.Subscribe(Subject, _sOpts, msgHandler))
            {
                ev.WaitOne();
            }

            return(sw.Elapsed);
        }
Exemple #8
0
        public void ReceiveAsync <T>(string queueName, Action <T> callback)
        {
            if (string.IsNullOrEmpty(queueName))
            {
                throw new ArgumentException("Invalid queue name", nameof(queueName));
            }

            var opts = StanSubscriptionOptions.GetDefaultOptions();

            opts.DurableName = queueName;

            if (!_typeSubscribers.ContainsKey(typeof(T)))
            {
                _typeSubscribers.Add(typeof(T), new Subscribers <T>());
            }

            ((Subscribers <T>)_typeSubscribers[typeof(T)]).Add(callback);

            _connection.Subscribe(queueName, opts, (sender, args) =>
            {
                var t = (T)BinaryFormatter.Deserialize(new MemoryStream(args.Message.Data));

                foreach (var subscriberCallback in (Subscribers <T>)_typeSubscribers[typeof(T)])
                {
                    subscriberCallback(t);
                }
            });
        }
Exemple #9
0
        public void Subscribe()
        {
            Assert.Equal(ConnState.CONNECTED, connection.NATSConnection.State);

            StanMsg <Person> received = null;

            using (var subscription = connection.Subscribe <Person>("subject",
                                                                    (sender, args) =>
            {
                received = args.Msg;
                received.Ack();
            }))
            {
                var jack = new Person()
                {
                    Id   = 1,
                    Name = "Jack",
                    Age  = 10,
                    Data = new byte[] { 0, 1, 2, 3, 4 }
                };

                connection.Publish("subject", jack);

                NeonHelper.WaitFor(() => received != null, TimeSpan.FromSeconds(5));
                Assert.True(received.Data == jack);
            }
        }
Exemple #10
0
 /// <summary>
 /// Subscribe will create an Asynchronous Subscriber with
 /// interest in a given subject, assign the handler, and immediately
 /// start receiving messages.
 /// </summary>
 /// <typeparam name="TMessage">The message type.</typeparam>
 /// <param name="connection">The conmnection.</param>
 /// <param name="subject">Subject of interest.</param>
 /// <param name="qgroup">Name of the queue group.</param>
 /// <param name="options">SubscriptionOptions used to create the subscriber.</param>
 /// <param name="handler">A message handler to process messages.</param>
 /// <returns>A new subscription.</returns>
 public static IStanSubscription Subscribe <TMessage>(this IStanConnection connection, string subject, string qgroup, StanSubscriptionOptions options, EventHandler <StanMsgHandlerArgs <TMessage> > handler)
     where TMessage : class, IRoundtripData, new()
 {
     return(connection.Subscribe(subject, qgroup, options,
                                 (sender, args) =>
     {
         handler?.Invoke(sender, args.Message.ToHandler <TMessage>());
     }));
 }
        private StanObservableSubscription(IStanConnection cn, string subject)
        {
            if (cn == null)
            {
                throw new ArgumentNullException(nameof(cn));
            }

            subscription = cn.Subscribe(subject, OnIncomingMessage);
        }
        public Program(string[] args)
        {
            var clientId = "";
            var topic    = "sample";

            if (args.Length > 1)
            {
                topic = args[1];
            }
            if (args.Length > 2)
            {
                clientId = args[2];
            }
            var cf      = new StanConnectionFactory();
            var options = StanOptions.GetDefaultOptions();

            options.ConnectTimeout = 1000;
            options.NatsURL        = "nats://*****:*****@localhost:4222";
            IStanConnection connection = cf.CreateConnection("test-cluster", clientId, options);

            if (args.Length > 0 && args[0] == "send")
            {
                while (true)
                {
                    connection.Publish(topic, Encoding.UTF8.GetBytes("Hello NATS " + Guid.NewGuid().ToString()));
                    Console.WriteLine("Message sent to topic: " + topic);
                    Thread.Sleep(500);
                }
            }
            else
            {
                var subName = "subscription-1";
                if (args.Length > 0)
                {
                    subName = args[0];
                }
                EventHandler <StanMsgHandlerArgs> eh = (sender, argsMsg) =>
                {
                    var body = Encoding.UTF8.GetString(argsMsg.Message.Data);
                    // TODO: Handle headers in right way
                    Console.WriteLine(body);
                    Thread.Sleep(1000);
                    argsMsg.Message.Ack();
                };

                var opts = StanSubscriptionOptions.GetDefaultOptions();
                opts.DurableName = subName;
                opts.ManualAcks  = true;
                opts.AckWait     = 60000;
                opts.MaxInflight = 1;
                IStanSubscription subscription = subscription = connection.Subscribe(topic, subName, opts, eh);
            }
        }
Exemple #13
0
        public void Start()
        {
            _connection = _connectionProvider.GetConnection();
            _cancellationTokenSource = new CancellationTokenSource();

            Task.Run(() =>
            {
                var opts         = StanSubscriptionOptions.GetDefaultOptions();
                opts.DurableName = $"{_config.Value.NatsConnection.ClientId}.Durable";

                _subscription = _connection.Subscribe("PostTechnology.EventBus", opts, MessageReceived);
            }, _cancellationTokenSource.Token);
        }
Exemple #14
0
        public NATSOrderRepository()
        {
            try
            {
                var cf      = new StanConnectionFactory();
                var options = StanOptions.GetDefaultOptions();
                options.NatsURL = "nats://localhost:4223";
                _stanConnection = cf.CreateConnection("test-cluster", CLIENTID, options);
                var subOptions = StanSubscriptionOptions.GetDefaultOptions();
                subOptions.DeliverAllAvailable();
                _stanConnection.Subscribe(EVENTSTREAM_SUBJECT, subOptions, (obj, args) =>
                {
                    try
                    {
                        string message        = Encoding.UTF8.GetString(args.Message.Data);
                        string[] messageParts = message.Split('#');

                        string eventTypeDescriptor =
                            $"Store.OrderProcessingService.Domain.Events.{messageParts[0]}";
                        Type eventType   = Type.GetType(eventTypeDescriptor);
                        string eventData = message.Substring(message.IndexOf('#') + 1);
                        dynamic e        = JsonSerializer.Deserialize(eventData, eventType);
                        if (_eventStreams.ContainsKey(e.OrderNumber))
                        {
                            _eventStreams[e.OrderNumber].Add(e);
                        }
                        else
                        {
                            _eventStreams.Add(e.OrderNumber, new List <BusinessEvent>()
                            {
                                e
                            });

                            Console.WriteLine($"Order #{e.OrderNumber} found during replay.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error: {ex.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation($"Starting hosted service \"{nameof(StanMessageReceiverService)}\".");
            }

            var task = Task.Run(() =>
            {
                List <Task> tasks = new List <Task>();
                Task t;

                _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

                foreach (var subscription in _messagingEvent.subscriptions)
                {
                    t = Task.Run(() =>
                    {
                        var topic = subscription.Key;

                        var theInstance = (IMessagingEvent)Activator.CreateInstance(_messagingEvent.subscriptions[topic], _serviceProvider);

                        EventHandler <StanMsgHandlerArgs> msgHandler = (sender, args) =>
                        {
                            theInstance.Process(args.Message.Data);
                        };

                        //while (!cancellationToken.IsCancellationRequested)
                        //{
                        IStanSubscription stanSubscription = _connection.Subscribe(topic, qGroup, sOpts, msgHandler);
                        //}
                    }, cancellationToken);

                    tasks.Add(t);
                }

                _tasks = tasks.ToArray();

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation($"Started hosted service \"{nameof(StanMessageReceiverService)}\".");
                }
            });

            return(task.IsCompleted ? Task.CompletedTask : task);
        }
        public void Start()
        {
            // connect to NATS
            var natsConnectionFactory = new ConnectionFactory();

            _natsConnection = natsConnectionFactory.CreateConnection("nats://localhost:4222");

            // connect to STAN
            var cf          = new StanConnectionFactory();
            var natsOptions = StanOptions.GetDefaultOptions();

            natsOptions.NatsURL = "nats://localhost:4223";
            _stanConnection     = cf.CreateConnection("test-cluster", "OrdersQueryService", natsOptions);

            // create queries subscription
            _natsConnection.SubscribeAsync("store.queries.*", QueryReceived);

            // create events subscription
            StanSubscriptionOptions stanOptions = StanSubscriptionOptions.GetDefaultOptions();

            stanOptions.DurableName = "OrdersQueryService";
            _stanConnection.Subscribe("store.events", stanOptions, EventReceived);
        }
Exemple #17
0
 public IStanSubscription Subscribe(string subject, EventHandler <StanMsgHandlerArgs> handler)
 {
     return(_stanSubscription = _stanClient.Subscribe(subject, handler));
 }