Exemple #1
0
        static void Main(string[] args)
        {
            string      serverURL = "nats://localhost:4222", clusterID = "test-cluster", clientID = "pub_client", subject = "foo_subject";
            StanOptions cOpts = StanOptions.GetDefaultOptions();

            cOpts.NatsURL = serverURL;
            using (var c = new StanConnectionFactory().CreateConnection(clusterID, clientID, cOpts))
            {
                Console.WriteLine("nats: connected serverURL='{0}', clusterID='{1}', clientID='{2}'", serverURL, clusterID, clientID);
                // publish message
                var ev     = new AutoResetEvent(false);
                var seq    = 0;
                var thread = new Thread(obj =>
                {
                    do
                    {
                        var msg = string.Format("message [#{0}]", ++seq);
                        c.Publish(subject, System.Text.Encoding.UTF8.GetBytes(msg));
                        Console.WriteLine("nats: published subject='{0}', message='{1}'", subject, msg);
                    } while (!ev.WaitOne(TimeSpan.FromSeconds(5)));
                });
                thread.Start();
                // wait for exit
                Console.WriteLine("program: press <enter> to exit...");
                Console.ReadLine();
                ev.Set();
                thread.Join();
            }
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            string clientId = $"producer-{Guid.NewGuid().ToString()}";

            StanOptions stanOptions = StanOptions.GetDefaultOptions();

            stanOptions.NatsURL = _natsOptions.Url;

            using (var c = new StanConnectionFactory()
                           .CreateConnection(_natsOptions.ClusterId, clientId, stanOptions))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    var message = new Message();
                    await _messageRepository.AddAsync(message);

                    var json = JsonSerializer.Serialize(message);
                    Console.WriteLine($"Отправка {json}");
                    c.Publish(_natsOptions.Subject, Encoding.UTF8.GetBytes(json));

                    await Task.Delay(1000);
                }

                _logger.LogInformation("Отправка сообщений отменена.");
            }
        }
Exemple #3
0
        private void Run(string[] args)
        {
            _clientId += Guid.NewGuid();

            Banner();

            _cOpts.NatsURL = Url;
            using var c    = new StanConnectionFactory().CreateConnection(ClusterId, _clientId, _cOpts);
            while (true)
            {
                long acksProcessed = 0;
                var  sw            = Stopwatch.StartNew();
                var  ev            = new AutoResetEvent(false);

                // async
                for (var i = 0; i < Count; i++)
                {
                    var guid = c.Publish(Subject, _payload, (obj, pubArgs) =>
                    {
                        if (Verbose)
                        {
                            Console.WriteLine("Received ack for message {0}", pubArgs.GUID);
                        }
                        if (!string.IsNullOrEmpty(pubArgs.Error))
                        {
                            Console.WriteLine("Error processing message {0}", pubArgs.GUID);
                        }

                        if (Interlocked.Increment(ref acksProcessed) == Count)
                        {
                            ev.Set();
                        }
                    });

                    if (Verbose)
                    {
                        Console.WriteLine("Published message with guid: {0}", guid);
                    }
                }

                ev.WaitOne();
                sw.Stop();

                Console.Write("Published {0} msgs with acknowledgements in {1} seconds ", Count, sw.Elapsed.TotalSeconds);
                Console.WriteLine("({0} msgs/second).", (int)(Count / sw.Elapsed.TotalSeconds));
            }
        }
Exemple #4
0
        private void Publish(string dataCentre)
        {
            var stanOptions = StanOptions.GetDefaultOptions();

            stanOptions.NatsURL = _natsClusterNodes[dataCentre];
            var       iteration = 0;
            const int numberOfMessagesToSend = 10;

            using var stanConnection = new StanConnectionFactory().CreateConnection(ClusterId, $"{Environment.MachineName.ToLower()}-{dataCentre}-sending", stanOptions);

            var messages = Enumerable.Range(1, numberOfMessagesToSend).Select(r =>
            {
                Console.WriteLine($"{dataCentre}: sent 'Sending message from test {++iteration}'");
                stanConnection.Publish("foo",
                                       System.Text.Encoding.UTF8.GetBytes($"Sending message from test {iteration}"));
                return(r);
            });

            Console.WriteLine($"Published {messages.Count()} messages...");
        }
Exemple #5
0
        static void Main(string[] args)
        {
            var clusterId = "test-cluster";
            var clientId  = Guid.NewGuid().ToString("N");

            using (var cn = new StanConnectionFactory().CreateConnection(clusterId, clientId))
            {
                var cts = new CancellationTokenSource();

                Task.Run(() =>
                {
                    var temperatures =
                        cn.Observe("temperatures")
                        .Where(m => m.Data?.Any() == true)
                        .Select(m => BitConverter.ToInt32(m.Data, 0));

                    temperatures.Subscribe(t => Console.WriteLine($"{t}C"));

                    temperatures.Subscribe(t => Console.WriteLine($"{(t * 9 / 5) + 32}F"));
                }, cts.Token);

                Task.Run(async() =>
                {
                    var rnd = new Random();

                    while (!cts.IsCancellationRequested)
                    {
                        cn.Publish("temperatures", BitConverter.GetBytes(rnd.Next(-10, 40)));

                        await Task.Delay(1000, cts.Token);
                    }
                }, cts.Token);

                Console.WriteLine("Hit any key to exit");
                Console.ReadKey();
                cts.Cancel();
            }
        }
Exemple #6
0
        public void Run(string[] args)
        {
            Stopwatch sw            = null;
            long      acksProcessed = 0;

            parseArgs(args);
            banner();

            cOpts.NatsURL = url;
            using (var c = new StanConnectionFactory().CreateConnection(clusterID, clientID, cOpts))
            {
                sw = Stopwatch.StartNew();

                if (async)
                {
                    AutoResetEvent ev = new AutoResetEvent(false);

                    for (int i = 0; i < count; i++)
                    {
                        string guid = c.Publish(subject, payload, (obj, pubArgs) =>
                        {
                            if (verbose)
                            {
                                Console.WriteLine("Recieved ack for message {0}", pubArgs.GUID);
                            }
                            if (!string.IsNullOrEmpty(pubArgs.Error))
                            {
                                Console.WriteLine("Error processing message {0}", pubArgs.GUID);
                            }

                            if (Interlocked.Increment(ref acksProcessed) == count)
                            {
                                ev.Set();
                            }
                        });

                        if (verbose)
                        {
                            Console.WriteLine("Published message with guid: {0}", guid);
                        }
                    }

                    ev.WaitOne();
                }
                else
                {
                    for (int i = 0; i < count; i++)
                    {
                        c.Publish(subject, payload);
                        if (verbose)
                        {
                            Console.WriteLine("Published message.");
                        }
                    }
                }

                sw.Stop();

                Console.Write("Published {0} msgs with acknowldegements in {1} seconds ", count, sw.Elapsed.TotalSeconds);
                Console.WriteLine("({0} msgs/second).",
                                  (int)(count / sw.Elapsed.TotalSeconds));
            }
        }