Ejemplo n.º 1
0
        private async Task RxSubscriber(string dataCentre, CancellationToken token)
        {
            var clusterId   = "test-cluster";
            var clientId    = Guid.NewGuid().ToString("N");
            var stanOptions = StanOptions.GetDefaultOptions();

            stanOptions.NatsURL = _natsClusterNodes[dataCentre];

            using var stanConnection = new StanConnectionFactory().CreateConnection(clusterId, clientId, stanOptions);

            var messagesSubject = stanConnection.Observe("foo");

            var loopCount = 0;

            messagesSubject.Subscribe(onNext: (message) =>
            {
                Console.WriteLine(
                    $"{dataCentre}: received '{System.Text.Encoding.UTF8.GetString(message.Data)}'. Redelivered: {message.Redelivered}. Sequence: {message.Sequence}");
                Console.WriteLine($"loopCount: {Interlocked.Increment(ref loopCount)}");
            });

            await Task.Delay(1000000, token);

            Console.WriteLine("Exiting subscription");
        }
Ejemplo n.º 2
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();
            }
        }