//Deadlock when i use simple stan configuration for cluster
        static async void DeadlockInStanOptions()
        {
            var cf = new StanConnectionFactory();

            var opts = StanOptions.GetDefaultOptions();

            opts.NatsURL      = "nats://127.0.0.1:4223,nats://127.0.0.1:4224";
            opts.PingInterval = 500;

            var opts2 = StanOptions.GetDefaultOptions();

            opts2.NatsURL = "nats://127.0.0.1:4222";


            using (var producer = cf.CreateConnection("test-cluster", "appname", opts))
                using (var consumer = cf.CreateConnection("test-cluster", "appname2", opts2))
                {
                    using (consumer.Subscribe("foo", (sender, handlerArgs) => Console.WriteLine(
                                                  System.Text.Encoding.UTF8.GetString(handlerArgs.Message.Data))))
                    {
                        Console.WriteLine("Connected. ConnServ {0}.", producer?.NATSConnection?.ConnectedUrl);

                        //first success send
                        producer?.Publish("foo", System.Text.Encoding.UTF8.GetBytes("first success hello"));

                        //stop connected stan container, simulation disconnect
                        var firstUrl             = producer?.NATSConnection?.ConnectedUrl;
                        var clusterContainerName = firstUrl.Contains("4224") ? "nats-2" : "nats-1";
                        DockerController.SendStopContainer(clusterContainerName);

                        //simulation of sending 10 messages to diconnected node
                        for (var i = 0; i < 10; i++)
                        {
                            var success = false;
                            while (!success)
                            {
                                Console.WriteLine($"Publishing.  ConnState {producer?.NATSConnection?.State}. Connected to {producer?.NATSConnection?.ConnectedUrl}");
                                try
                                {
                                    producer?.Publish("foo", System.Text.Encoding.UTF8.GetBytes("hello"));
                                    success = true;
                                }
                                catch (Exception e)
                                {
                                    System.Console.WriteLine("exception:  {0}", e.Message);
                                }

                                await Task.Delay(1000);
                            }
                        }

                        DockerController.SendStartContainer(clusterContainerName);
                    }
                }
        }
Example #2
0
        static void Main(string[] args)
        {
            string clientId = $"producer-{Guid.NewGuid().ToString()}";

            var         cf      = new StanConnectionFactory();
            StanOptions options = StanOptions.GetDefaultOptions();

            options.NatsURL = "nats://localhost:4222";

            using (var c = cf.CreateConnection("test-cluster", clientId, options))
            {
                do
                {
                    var opts = StanSubscriptionOptions.GetDefaultOptions();
                    opts.StartWithLastReceived();
                    var s = c.Subscribe("nats.streaming.demo.client", opts, (obj, arguments) =>
                    {
                        string message = Encoding.UTF8.GetString(arguments.Message.Data);
                        Console.WriteLine(message);
                    });

                    c.Publish("nats.streaming.demo", Encoding.UTF8.GetBytes("Published from the publisher"));
                    Thread.Sleep(10000);
                } while (true);
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            // run docker run --rm --name natstest -p 4222:4222 -p 8222:8222 nats-streaming -store file -dir ./data --max_msgs 0 --max_bytes 0 --cluster_id scarsnatscluster
            var cf = new StanConnectionFactory();
            var c  = cf.CreateConnection("mynatscluster", "my-publish");

            // when the server responds with an acknowledgement, this
            // handler will be invoked.
            EventHandler <StanAckHandlerArgs> ackHandler = (obj, natsargs) =>
            {
                if (!string.IsNullOrEmpty(natsargs.Error))
                {
                    Console.WriteLine("Published Msg {0} failed: {1}",
                                      natsargs.GUID, natsargs.Error);
                }

                // handle success - correlate the send with the guid..
                //Console.WriteLine("Published msg {0} was stored on the server.");
            };

            int i = 0;

            // returns immediately
            while (true)
            {
                string guid = c.Publish("my.log.error", System.Text.Encoding.UTF8.GetBytes(i.ToString() + " - This error sucks!"), ackHandler);
                Console.WriteLine("{1} - Published msg {0} was stored on the server.", guid, i.ToString());
                i++;
                System.Threading.Thread.Sleep(new TimeSpan(0, 0, 5));
            }
        }
        //  .\nats-streaming-server.exe -cid cluster-teste-local -store file -dir dados-cluster-teste-local

        static void Main(string[] args)
        {
            string CLUSTER_ID = "cluster-teste-local";
            string CLIENT_ID  = "Producer-" + DateTime.Now.Second;
            string SUBJECT    = "subject-test";
            string URL_NATS   = "nats://localhost:4222";

            var         cf          = new StanConnectionFactory();
            StanOptions stanOptions = StanOptions.GetDefaultOptions();

            stanOptions.NatsURL = URL_NATS;

            Console.WriteLine($"Connecting (URL_NATS = {URL_NATS}) ...");
            Console.WriteLine($"CLUSTER_ID = {CLUSTER_ID}");
            Console.WriteLine($"CLIENT_ID = {CLIENT_ID}");


            using (var c = cf.CreateConnection(CLUSTER_ID, CLIENT_ID, stanOptions))
            {
                Random r = new Random();

                while (true)
                {
                    var msgId = r.Next();

                    string msg = CLIENT_ID + "-" + msgId.ToString();
                    c.Publish(SUBJECT, Encoding.UTF8.GetBytes(msg));

                    Console.WriteLine($"Msg published on {SUBJECT} : {msg}");

                    Thread.Sleep(1000);
                }
            }
        }
Example #5
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);
        }
Example #6
0
        public IStanConnection GetIStanConnection()
        {
            var options = StanOptions.GetDefaultOptions();

            options.NatsURL = _appConfig.Value.NatsConnection.ConnectionUrl;

            return(_connectionFactory.CreateConnection(_appConfig.Value.NatsConnection.ClusterId, _appConfig.Value.App.AppName, options));
        }
Example #7
0
        public static void Main(string[] args)
        {
            Console.WriteLine($"NATS Monitor Tool - v1.2");

            if (args == null || !args.Any())
            {
                Console.WriteLine("Need argument!");
                Environment.Exit(1);
            }


            _eventName = args[0];
            if (args.Length > 1)
            {
                URL = $"nats://{args[1]}";
            }

            var scf     = new StanConnectionFactory();
            var options = StanOptions.GetDefaultOptions();

            options.NatsURL = URL;
            var clientId       = Environment.MachineName;
            var stanConnection = scf.CreateConnection("events-streaming",
                                                      $"{clientId}-{Guid.NewGuid()}",
                                                      options);

            var subOptions = StanSubscriptionOptions.GetDefaultOptions();

            subOptions.DurableName = Environment.MachineName;
            subOptions.StartAt(DateTime.UtcNow.AddMinutes(-1));

            Console.WriteLine($"Starting connection to {_eventName} at {URL}");
            using (var sub = stanConnection.Subscribe(_eventName, subOptions, (sender, handlerArgs) =>
            {
                WriteToConsole(format_json(Encoding.UTF8.GetString(handlerArgs.Message.Data)));
                _eventCount++;
            }))
            {
                while (true)
                {
                    Thread.Sleep(1000);

                    if (!Console.KeyAvailable)
                    {
                        continue;
                    }

                    var key = Console.ReadKey(true);
                    if (key.Modifiers.HasFlag(ConsoleModifiers.Control) && key.Key == ConsoleKey.S)
                    {
                        sub.Close();
                        WriteToConsole("Exiting application...");
                        Environment.Exit(0);
                    }
                }
            }
        }
Example #8
0
        void InitStanClient()
        {
            var stanConnectionFactory = new StanConnectionFactory();

            _stanClient = stanConnectionFactory.CreateConnection(_options.ClusterId, _options.ClientId, _stanOptions);

            _stanSubscriptionOptions             = StanSubscriptionOptions.GetDefaultOptions();
            _stanSubscriptionOptions.DurableName = _options.StanSubscriptionOptions.DurableName;
        }
Example #9
0
        public IStanConnection GetConnection()
        {
            var natsConfig = _appConfig.Value.NatsConnection;

            var options = StanOptions.GetDefaultOptions();

            options.NatsURL = natsConfig.Url;
            return(_connectionFactory.CreateConnection(natsConfig.ClusterId, natsConfig.ClientId, options));
        }
Example #10
0
        /// <summary>
        /// Establishes the server connection.
        /// </summary>
        private void Connect()
        {
            var factory = new StanConnectionFactory();
            var retry   = new LinearRetryPolicy(exception => true, 20, TimeSpan.FromSeconds(0.5));

            retry.Invoke(
                () =>
            {
                Connection = factory.CreateConnection("test-cluster", nameof(NatsStreamingFixture));
            });
        }
        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);
            }
        }
Example #12
0
        IStanConnection getConnection()
        {
            IStanConnection conn = null;

            try
            {
                conn = StanConnectionFactory.CreateConnection(clusterID, clientID, cOpts);
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Warn(ex, "Creat nats connection fail!");
            }
            return(conn);
        }
Example #13
0
        static void Main(string[] args)
        {
            string CLUSTER_ID   = "cluster-teste-local";
            string CLIENT_ID    = "Consumer-" + DateTime.Now.Second;
            string DURABLE_NAME = "durable-queue";
            string SUBJECT      = "subject-test";
            string QUEUE_GROUP  = "queue-group-test";
            string URL_NATS     = "nats://localhost:4222";


            var         cf          = new StanConnectionFactory();
            StanOptions stanOptions = StanOptions.GetDefaultOptions();

            stanOptions.NatsURL = URL_NATS;

            Console.WriteLine($"Connecting (URL_NATS = {URL_NATS}) ...");
            Console.WriteLine($"CLUSTER_ID = {CLUSTER_ID}");
            Console.WriteLine($"CLIENT_ID = {CLIENT_ID}");

            using (var c = cf.CreateConnection(CLUSTER_ID, CLIENT_ID, stanOptions))
            {
                var subscriptionOpts = StanSubscriptionOptions.GetDefaultOptions();

                subscriptionOpts.DurableName = DURABLE_NAME;
                subscriptionOpts.ManualAcks  = true;
                subscriptionOpts.MaxInflight = 1;

                var cts = new CancellationTokenSource();

                Task.Run(() =>
                {
                    c.Subscribe(SUBJECT, QUEUE_GROUP, subscriptionOpts, (obj, args) =>
                    {
                        string msg = Encoding.UTF8.GetString(args.Message.Data);

                        Console.WriteLine($"Msg received on {SUBJECT} : {msg}");

                        args.Message.Ack();
                    });
                }, cts.Token);



                Console.WriteLine("Waiting...  [press any key to exit]");
                Console.ReadKey();

                cts.Cancel();
            }
        }
Example #14
0
        public void Setup(string appname)
        {
            var cf = new StanConnectionFactory();

            _connection = cf.CreateConnection("test-cluster", appname);

            _connection.NATSConnection.Opts.DisconnectedEventHandler += (sender, args) =>
            {
                OnDisconnected?.Invoke(this, new OnDisconnectedHandlerArgs(args.Conn.State));
            };

            _connection.NATSConnection.Opts.ClosedEventHandler += (sender, args) =>
            {
                OnClosed?.Invoke(this, new OnClosedHandlerArgs(args.Conn.State));
            };
        }
Example #15
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}");
            }
        }
Example #16
0
        static void Main(string[] args)
        {
            // run docker run --rm --name natstest -p 4222:4222 -p 8222:8222 nats-streaming -store file -dir ./data --max_msgs 0 --max_bytes 0 --cluster_id scarsnatscluster
            EventHandler <StanMsgHandlerArgs> ackHandler = (obj, natsargs) =>
            {
                Console.WriteLine("Message: {0} - {1} - {2}", natsargs.Message.Subject,
                                  System.Text.Encoding.UTF8.GetString(natsargs.Message.Data), natsargs.Message.TimeStamp.ToString());
            };

            var opts = StanSubscriptionOptions.GetDefaultOptions();

            opts.DeliverAllAvailable();
            //opts.StartAt(22);
            var cf = new StanConnectionFactory();
            var c  = cf.CreateConnection("mynatscluster", "my-reader");
            var s  = c.Subscribe("my.log.error", opts, ackHandler);
        }
Example #17
0
        public void Start()
        {
            _repo = new SQLServerOrderRepository();

            // connect to NATS
            var natsConnectionFactory = new ConnectionFactory();

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

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

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

            // create commands subscription
            _commandsSubscription = _natsConnection.SubscribeAsync("store.commands.*", CommandReceived);
        }
Example #18
0
        static void Main(string[] args)
        {
            string clientId = $"producer-{Guid.NewGuid().ToString()}";

            var         cf      = new StanConnectionFactory();
            StanOptions options = StanOptions.GetDefaultOptions();

            options.NatsURL = "nats://localhost:4223";

            using (var c = cf.CreateConnection("test-cluster", clientId, options))
            {
                for (int i = 1; i <= 25; i++)
                {
                    string message = $"[{DateTime.Now.ToString("hh:mm:ss:fffffff")}] Message {i}";
                    Console.WriteLine($"Sending {message}");

                    c.Publish("nats.streaming.demo", Encoding.UTF8.GetBytes(message));
                }
            }
        }
Example #19
0
        private IStanConnection GetConnection()
        {
            var clientId = _natsOptions.Value.ClientId?.Replace(".", "_");
            var options  = StanOptions.GetDefaultOptions();

            options.NatsURL = _natsOptions.Value.NatsUrl;

            options.ConnectionLostEventHandler = (_, args) =>
            {
                SetUnrecoverableState(args.ConnectionException ?? new Exception("NATS connection was lost"));
            };

            //fix https://github.com/nats-io/csharp-nats-streaming/issues/28
            options.PubAckWait = 30000;

            var cf = new StanConnectionFactory();

            _connection = cf.CreateConnection(_natsOptions.Value.Cluster, clientId + Guid.NewGuid(), options);

            return(_connection);
        }
Example #20
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: consumer <clientid>");
                return;
            }

            string clientId = args[0];

            var cf = new StanConnectionFactory();

            StanOptions options = StanOptions.GetDefaultOptions();

            options.NatsURL = "nats://localhost:4222";

            using (var c = cf.CreateConnection("test-cluster", clientId, options))
            {
                var opts = StanSubscriptionOptions.GetDefaultOptions();

                //opts.DeliverAllAvailable();
                //opts.StartAt(15);
                //opts.StartAt(TimeSpan.FromSeconds(10));
                //opts.StartAt(new DateTime(2019, 9, 18, 9, 0, 0));
                //opts.StartWithLastReceived();
                //opts.DurableName = "durable";

                var s = c.Subscribe("nats.streaming.demo", opts, (obj, args) =>
                {
                    string message = Encoding.UTF8.GetString(args.Message.Data);
                    Console.WriteLine($"[#{args.Message.Sequence}] {message}");
                });

                Console.WriteLine($"Consumer with client id '{clientId}' started. Press any key to quit...");
                Console.ReadKey(true);

                //s.Unsubscribe();
                c.Close();
            }
        }
        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);
        }
Example #22
0
        private IStanConnection GetConnection()
        {
            var natsUrl  = _configuration.GetSection("Messaging").GetSection("Nats")["natsUrl"];
            var cluster  = _configuration.GetSection("Messaging").GetSection("Nats")["cluster"];
            var clientId = _configuration.GetSection("Messaging").GetSection("Nats")["clientId"]
                           ?.Replace(".", "_");
            var options = StanOptions.GetDefaultOptions();

            options.NatsURL = natsUrl;

            options.ConnectionLostEventHandler = (obj, args) =>
            {
                SetUnrecoverableState(args.ConnectionException ?? new Exception("NATS connection was lost"));
            };

            //fix https://github.com/nats-io/csharp-nats-streaming/issues/28
            options.PubAckWait = 30000;

            var cf = new StanConnectionFactory();

            _connection = cf.CreateConnection(cluster, clientId + Guid.NewGuid(), options);

            return(_connection);
        }
Example #23
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: consumer <clientid>");
                return;
            }

            string clientId = args[0];

            var cf = new StanConnectionFactory();

            StanOptions options = StanOptions.GetDefaultOptions();

            options.NatsURL = "nats://localhost:4222";
            using (var c = cf.CreateConnection("test-cluster", clientId, options))
            {
                var opts = StanSubscriptionOptions.GetDefaultOptions();
                opts.StartWithLastReceived();
                Task.Run(() =>
                {
                    var s = c.Subscribe("nats.streaming.demo", opts, (obj, arguments) =>
                    {
                        string message = Encoding.UTF8.GetString(arguments.Message.Data);
                        Console.WriteLine(message);
                        c.Publish("nats.streaming.demo.client", Encoding.UTF8.GetBytes("publishing from consumer " + clientId));
                    });
                });
                Console.WriteLine($"Consumer with client id '{clientId}' started. Press any key to quit...");
                Console.ReadKey(true);

                //s.Unsubscribe();
                c.Close();
            }
            Console.ReadLine();
        }
 IStanConnection getConnection()
 {
     return(StanConnectionFactory.CreateConnection(clusterID, clientID, cOpts));
 }
Example #25
0
 public IStanConnection GetStanConnection(StanOptions opts, string clusterId = null, string clientId = null)
 => StanConnectionFactory.CreateConnection(clusterId ?? ClusterId, clientId ?? ClientId, opts);
Example #26
0
 public IStanConnection GetStanConnection(TestServerInfo serverInfo, string clusterId = null, string clientId = null)
 => StanConnectionFactory.CreateConnection(clusterId ?? ClusterId, clientId ?? ClientId, GetStanTestOptions(serverInfo));