static async Task ReaderText(NatsConnection connection, CancellationToken cancellationToken) { var history = new Queue <(int count, long time)>(); var counter = 0; var prev = 0; var watch = Stopwatch.StartNew(); await foreach (var message in connection.SubscribeText("HELLO", cancellationToken: cancellationToken)) { counter++; if (counter % 1_000_000 != 0) { continue; } watch.Stop(); history.Enqueue((counter - prev, watch.ElapsedMilliseconds)); prev = counter; if (history.Count > 10) { history.Dequeue(); } var count = history.Sum(h => h.count); var time = history.Sum(h => h.time); Console.WriteLine($"{message} - {count / (double) time * 1000}"); watch = Stopwatch.StartNew(); } }
/// <summary> /// Opens the component with given connection and credential parameters. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public async override Task OpenAsync(string correlationId) { if (IsOpen()) { return; } if (_connection == null) { _connection = CreateConnection(); _localConnection = true; } if (_localConnection) { await _connection.OpenAsync(correlationId); } if (!_connection.IsOpen()) { throw new InvalidStateException(correlationId, "CONNECT_FAILED", "NATS connection is not opened"); } await base.OpenAsync(correlationId); _opened = true; }
static async Task WriterText(NatsConnection connection, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { await connection.PublishTextAsync("HELLO", "HELLO WORLD", cancellationToken : cancellationToken); } }
static async Task MultiplyListenerAsync(NatsConnection connection, CancellationToken cancellationToken) { await foreach (var request in connection.Subscribe <Request>("multiply", cancellationToken: cancellationToken)) { await connection.PublishObjectAsync(request.ReplyTo, new Response { Result = request.Payload.X * request.Payload.Y }, cancellationToken : cancellationToken); } }
static async Task ListenerTask(NatsConnection connection, CancellationToken cancellationToken) { await foreach (var text in connection.SubscribeText("long.message", cancellationToken: cancellationToken)) { Console.WriteLine("Received string {0} characters long", text.Length); break; } }
public Worker(ILogger <Worker> logger, NatsConnection natsConnection) { this.logger = logger; this.natsConnection = natsConnection; eventExecuteTime = Metrics.CreateGauge("nats_event_execution_time", "Counts total execution time for handling NATS message"); eventCount = Metrics.CreateCounter("nats_event_total", "NATS Events Total", new CounterConfiguration { LabelNames = new[] { "type", "status" } }); }
static async Task Main(string[] args) { var options = new NatsDefaultOptions { Echo = true // Without echo this test does not work! On production you might want to keep it disabled }; var connection = new NatsConnection(options); connection.ConnectionException += (sender, exception) => Console.WriteLine($"ConnectionException : {exception}"); connection.StatusChange += (sender, status) => Console.WriteLine($"Connection status changed to {status}"); connection.ConnectionInformation += (sender, information) => Console.WriteLine($"Connection information {JsonSerializer.Serialize(information)}"); var cancellation = new CancellationTokenSource(); var addListenerTask = AddListenerAsync(connection, cancellation.Token); var multiplyListenerTask = MultiplyListenerAsync(connection, cancellation.Token); var senderTask = SenderAsync(connection, cancellation.Token); await connection.ConnectAsync(); Console.ReadKey(); cancellation.Cancel(); try { await addListenerTask; } catch (OperationCanceledException) { } try { await multiplyListenerTask; } catch (OperationCanceledException) { } try { await senderTask; } catch (OperationCanceledException) { } Console.ReadKey(); await connection.DisposeAsync(); Console.ReadKey(); }
private NatsConnection CreateConnection() { var connection = new NatsConnection(); if (_config != null) { connection.Configure(_config); } if (_references != null) { connection.SetReferences(_references); } return(connection); }
static async Task SenderTask(NatsConnection connection, CancellationToken cancellationToken) { // Not very efficient, but it's the idea ;) var sb = new StringBuilder(); while (sb.Length < 900_000) { sb.Append((sb.Length % 10).ToString()); } var str = sb.ToString(); Console.WriteLine("Sending string {0} characters long", str.Length); await connection.PublishTextAsync("long.message", str, cancellationToken : cancellationToken); }
/// <summary> /// SetReferences are sets references to dependent components. /// </summary> /// <param name="references">References to be set</param> public override void SetReferences(IReferences references) { base.SetReferences(references); _references = references; _dependencyResolver.SetReferences(references); // Get connection _connection = _dependencyResolver.GetOneOptional <NatsConnection>("connection"); // Or create a local one if (_connection == null) { _connection = CreateConnection(); _localConnection = true; } else { _localConnection = false; } }
static async Task Main(string[] args) { var options = new NatsDefaultOptions { Echo = true // Without echo this test does not work! On production you might want to keep it disabled }; var connection = new NatsConnection(options); connection.ConnectionException += (sender, exception) => Console.WriteLine($"ConnectionException : {exception}"); connection.StatusChange += (sender, status) => Console.WriteLine($"Connection status changed to {status}"); connection.ConnectionInformation += (sender, information) => Console.WriteLine($"Connection information {JsonSerializer.Serialize(information)}"); await connection.ConnectAsync(); var cancellation = new CancellationTokenSource(); var listener = ListenerTask(connection, cancellation.Token); var sender = SenderTask(connection, cancellation.Token); await sender; await listener; }
static async Task SenderAsync(NatsConnection connection, CancellationToken cancellationToken) { var random = new Random(); while (!cancellationToken.IsCancellationRequested) { var request = new Request { X = random.Next(1, 100), Y = random.Next(1, 100) }; var add = await connection.RequestObject <Request, Response>("add", request, cancellationToken : cancellationToken); Console.WriteLine($"{request.X} + {request.Y} = {add.Result}"); var multiply = await connection.RequestObject <Request, Response>("multiply", request, cancellationToken : cancellationToken); Console.WriteLine($"{request.X} * {request.Y} = {multiply.Result}"); await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); } }
static async Task Main(string[] args) { var options = new NatsDefaultOptions { Echo = true // Without echo this test does not work! On production you might want to keep it disabled }; options.Serializer = new NatsAsciiSerializer(); var connection = new NatsConnection(options); connection.ConnectionException += (sender, exception) => Console.WriteLine($"ConnectionException : {exception}"); connection.StatusChange += (sender, status) => Console.WriteLine($"Connection status changed to {status}"); connection.ConnectionInformation += (sender, information) => Console.WriteLine($"Connection information {JsonSerializer.Serialize(information)}"); var cancellation = new CancellationTokenSource(); await connection.ConnectAsync(); var count = 0; while (connection.Status != NatsStatus.Connected) { await Task.Delay(50, cancellation.Token); count++; if (count > 100) { Console.WriteLine("Could not connect to nats server"); await connection.DisposeAsync(); return; } } var readerTypedTask = Task.Run(() => ReaderText(connection, cancellation.Token)); var writerTask = Task.Run(() => WriterText(connection, cancellation.Token)); Console.ReadKey(); cancellation.Cancel(); try { await readerTypedTask; } catch (OperationCanceledException) { } try { await writerTask; } catch (OperationCanceledException) { } Console.ReadKey(); await connection.DisposeAsync(); Console.ReadKey(); }
static async Task Main(string[] args) { var options = new NatsDefaultOptions { Serializer = new NatsMessagePackSerializer(), Echo = true, // Without echo this test does not work! On production you might want to keep it disabled RequestTimeout = TimeSpan.FromSeconds(2), }; var connection = new NatsConnection(options); connection.ConnectionException += (sender, exception) => Console.WriteLine($"ConnectionException : {exception.Message}"); connection.StatusChange += (sender, status) => Console.WriteLine($"Connection status changed to {status}"); connection.ConnectionInformation += (sender, information) => Console.WriteLine($"Connection information {JsonSerializer.Serialize(information)}"); var cancellation = new CancellationTokenSource(); var listenerTask = connection.StartContractServer <IContract>(new Server(), cancellation.Token, "IContract"); await connection.ConnectAsync(); var count = 0; while (connection.Status != NatsStatus.Connected) { await Task.Delay(50, cancellation.Token); count++; if (count <= 100) { continue; } Console.WriteLine("Could not connect to nats server"); await connection.DisposeAsync(); return; } var client = connection.GenerateContractClient <IContract>("IContract"); var result = await client.MultiplyAsync(10, 10); Console.WriteLine("Multiply Result: {0}", result); result = client.Add(10, 10); Console.WriteLine("Add Result: {0}", result); result = await client.RandomAsync(); Console.WriteLine("RandomAsync Result: {0}", result); result = client.Random(); Console.WriteLine("Random Result: {0}", result); await client.SayAsync("Hello Async World"); client.Say("Hello Sync World"); await client.FireAndForget(1, 2, 3); Console.WriteLine("After FireAndForget - Note that ThrowException will not execute until after FireAndForget finishes (server is single threaded)"); Console.WriteLine("Request timeout test"); try { await client.Timeout(); Console.WriteLine("ERROR: The Timeout call should have timed out!"); } catch (Exception ex) { Console.WriteLine("Expected exception: {0}", ex.InnerException?.Message ?? ex.Message); } try { client.ThrowException(); } catch (Exception ex) { Console.WriteLine("Expected exception: {0}", ex.Message); } try { await client.ThrowExceptionOnMethodWithReturn(); } catch (Exception ex) { Console.WriteLine("Expected exception: {0}", ex.Message); } Console.ReadKey(); cancellation.Cancel(); try { await listenerTask; } catch (OperationCanceledException) { } await connection.DisposeAsync(); }
static async Task Main(string[] args) { var options = new NatsDefaultOptions { SenderQueueLength = 5000, ReceiverQueueLength = 500, }; await using var readerConnection = new NatsConnection(options); readerConnection.ConnectionException += (sender, exception) => Console.WriteLine($"ConnectionException : {exception}"); readerConnection.StatusChange += (sender, status) => Console.WriteLine($"Connection status changed to {status}"); readerConnection.ConnectionInformation += (sender, information) => Console.WriteLine($"Connection information {JsonSerializer.Serialize(information)}"); var cancellation = new CancellationTokenSource(); await readerConnection.ConnectAsync(); var count = 0; while (readerConnection.Status != NatsStatus.Connected) { await Task.Delay(50, cancellation.Token); count++; if (count > 100) { Console.WriteLine("Could not connect to nats server"); await readerConnection.DisposeAsync(); return; } } var tasks = new[] { Task.Run(() => Reader(readerConnection, cancellation.Token), cancellation.Token) }.Concat(Enumerable.Range(0, 5).Select(_ => Task.Run(() => Writer(options, cancellation.Token), cancellation.Token))).ToArray(); var frequency = (double)Stopwatch.Frequency; while (!Console.KeyAvailable) { Console.Write($"\rMessages processed {_timings.Count} ({_timings.Count / ((Stopwatch.GetTimestamp() - _started) / frequency):N2} messages/sec) {readerConnection.ReceiverQueueSize} "); await Task.Delay(1000, cancellation.Token); } cancellation.Cancel(); try { Task.WaitAll(tasks); } catch { } Console.WriteLine($"Measured {_timings.Count} messages in {(_ended - _started) / frequency:N2} seconds ({_timings.Count / ((_ended - _started) / frequency):N2} messages/sec)"); _timings.Sort(); var ms = Stopwatch.Frequency / 1000d; Console.WriteLine("Latencies:"); Console.WriteLine($"Slowest: {_timings[^1] / ms:N2}ms");
public NatsService(ILogger <NatsService> logger, NatsConnection natsConnection) { this.logger = logger; this.natsConnection = natsConnection; }