public static Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Publisher", cnInfo)) { client.Connect(); while (true) { Console.WriteLine("Say what? (blank=quit)"); var message = Console.ReadLine(); if (string.IsNullOrWhiteSpace(message)) { break; } int n; Console.WriteLine("How many? (blank=quit)"); if (!int.TryParse(Console.ReadLine(), out n)) { break; } client.PubMany(p => { for (var c = 0; c < n; c++) { p.Pub("demo", message); } }); } } return(Task.CompletedTask); }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample4", cnInfo)) { client.Connect(); //Observer lets you react on exceptions etc //Send "fail" to have it fail await client.SubWithObserverAsync( "demo", new DelegatingObserver <MsgOp>( msgOp => { var msg = msgOp.GetPayloadAsString(); if (msg == "fail") { throw new Exception("Oh no!"); } Console.WriteLine(msg); }, ex => Console.WriteLine($"Bad times! {ex}"))); //You can have an "generic" handler for exceptions as well client.MsgOpStream.OnException = (msgOp, ex) => Console.WriteLine($"Worse times! {ex}"); //If logging is all you need you can also hook into //LoggerManager.Resolve Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public async Task Given_multiple_responders_exists_When_requesting_It_should_return_one_response() { var value = Guid.NewGuid().ToString("N"); var responderReplyingCount = 0; var responderReplyCount = 0; _requester.MsgOpStream.Subscribe(msgOp => Interlocked.Increment(ref responderReplyCount)); _responder.Sub("getValue", stream => stream.Subscribe(msg => { Interlocked.Increment(ref responderReplyingCount); _responder.Pub(msg.ReplyTo, msg.GetPayloadAsString()); })); MsgOp response; using (var responder2 = new NatsClient(ConnectionInfo)) { responder2.Connect(); responder2.Sub("getValue", stream => stream.Subscribe(msg => { Interlocked.Increment(ref responderReplyingCount); responder2.Pub(msg.ReplyTo, msg.GetPayloadAsString()); })); response = await _requester.RequestAsync("getValue", value); } response.GetPayloadAsString().Should().Be(value); responderReplyCount.Should().Be(1); responderReplyingCount.Should().Be(2); }
private static async Task <NatsClient> Connect(int port = 4222) { var hostname = _isCi ? $"nats-{port - 4222}" : "localhost"; var cancellationToken = new CancellationTokenSource(_timeout).Token; return(await NatsClient.Connect(hostname, port, _natsOptions, cancellationToken)); }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample8", cnInfo)) { //Subscribe directly to MsgOpStream client.MsgOpStream .Where(msgOp => msgOp.Subject == "demo.a") .Select(msgOp => msgOp.GetPayloadAsString()) .Subscribe(msg => Console.WriteLine($"A: {msg}")); client.MsgOpStream .Where(msgOp => msgOp.Subject == "demo.b") .Select(msgOp => msgOp.GetPayloadAsString()) .Subscribe(msg => Console.WriteLine($"B: {msg}")); //OpStream gets all incoming Ops. Like MsgOp, Ping, Pong... client.OpStream .OfType <MsgOp>() .Select(msgOp => msgOp.GetAsString().Length) .Subscribe(len => Console.WriteLine($"Len: {len}")); client.Connect(); //Tell NATS server we are interested in all subjects //under "demo". So we only have one NATS Server subscription await client.SubAsync("demo.>"); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
/// <summary> /// Starts the subscription /// </summary> /// <summary> /// Starts the subscription /// </summary> public async Task Start() { if (_disposed) { throw new ObjectDisposedException($"{typeof(JsonRpcSubscription).FullName}@{this.GetHashCode()}"); } if (!_client.IsConnected) { _client.Connect(); } if (_subscription != null) { await _client.UnsubAsync(_subscription); _subscription = null; } _subscription = await _client.SubAsync(_sInfo, stream => stream.Subscribe(msg => { try { byte[] resp = OnMessage(msg.Payload); _client.Pub(msg.ReplyTo, resp); } catch (Exception ex) { _logger?.LogError(ex, "Error publishing NATS message"); } }, error => { _logger?.LogError(error, "Fatal error in NATS subscription handler"); })); }
/// <summary> /// Serves the asynchronous. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public async Task <JsonRpcResponse> ServeAsync(JsonRpcRequest request) { if (_disposed) { throw new ObjectDisposedException(typeof(JsonRpcServer).Name); } using (var client = new NatsClient(_connectionInfo)) { try { client.Connect(); var response = await client.RequestAsync(request.Method, EncodeRequest(request), _timeout); var data = DecodeResponse(response.Payload); return(data); } catch (NatsRequestTimedOutException e) { throw new JsonRpcException(ErrorCode.InternalError, e.Message); } catch (Exception ex) { throw new JsonRpcException(ErrorCode.InternalError, ex.Message); } } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Publisher", cnInfo)) { client.Connect(); while (true) { Console.WriteLine("Say what? (blank=quit)"); var message = Console.ReadLine(); if (string.IsNullOrWhiteSpace(message)) { break; } Console.WriteLine("To what \"Child\" Subject? (blank=quit)"); var subject = Console.ReadLine(); if (string.IsNullOrWhiteSpace(subject)) { break; } await client.PubAsync($"demo.{subject}", message); } } }
/// <summary> /// Create Nats Client from connection string /// </summary> /// <param name="connstring">Connection String</param> /// <returns>Returns NatsClient</returns> public NatsClient CreateNatsClient(string connstring) { NatsClient client = new NatsClient(); client.Connect(connstring); return(client); }
public ClientRequestTests() { _requester = new NatsClient(ConnectionInfo); _requester.Connect(); _responder = new NatsClient(ConnectionInfo); _responder.Connect(); }
public ClientUnSubTests() { _client1 = new NatsClient(ConnectionInfo); _client1.Connect(); _client2 = new NatsClient(ConnectionInfo); _client2.Connect(); _client3 = new NatsClient(ConnectionInfo); _client3.Connect(); }
public NatsEventBus(string[] hosts) { var _hosts = hosts.ToList().Select(dl => new Host(dl, 4222)).ToArray(); var connectionInfo = new ConnectionInfo( //Hosts to use. When connecting, will randomize the list //and try to connect. First successful will be used. _hosts); //docker run -p 4222:4222 -p 8222:8222 -ti nats:latest client = new NatsClient(connectionInfo); client.Connect(); }
protected override async Task DoWork(PairConfig pair, CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { using (BinanceSocketClient client = new BinanceSocketClient()) { ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString); using (NatsClient natsClient = new NatsClient(cnInfo)) { if (!natsClient.IsConnected) { natsClient.Connect(); } CallResult <UpdateSubscription> successKline = null; successKline = client.SubscribeToTradeUpdates(pair.Symbol, async(data) => { Trade trade = data.ToEntity(); if (!_settings.Value.DisadleDealsSaving) { long id = await _tradesProcessor.Create(trade); } await natsClient.PubAsJsonAsync(_settings.Value.TradesQueueName, new Notification <Trade>() { Code = ActionCode.CREATED.Code, Payload = trade }); }); successKline.Data.ConnectionLost += () => { _logger.LogError($"Connection to {Exchange} is lost"); }; successKline.Data.ConnectionRestored += (data) => { _logger.LogError($"Connection to {Exchange} is Restored"); }; while (!stoppingToken.IsCancellationRequested) { } natsClient.Disconnect(); await client.Unsubscribe(successKline.Data); } } } catch (Exception ex) { _logger.LogError($"{Exchange.Description} Trades service failed with message {ex.Message}", ex); } } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString); using (NatsClient natsClient = new NatsClient(cnInfo)) { if (!natsClient.IsConnected) { natsClient.Connect(); } await natsClient.SubAsync(_settings.Value.CandlesQueueName, stream => stream.Subscribe(msg => { try { Task.Run(async() => await Process(msg, natsClient)); } catch (Exception ex) { _logger.LogError($"TradingProcessor failed with message: {ex.Message}", ex); } })); natsClient.Events.OfType <ClientDisconnected>().Subscribe(ev => { Console.WriteLine($"Client was disconnected due to reason '{ev.Reason}'"); if (!cnInfo.AutoReconnectOnFailure) { ev.Client.Connect(); } }); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(TimeSpan.FromSeconds(1)); } natsClient.Disconnect(); } } catch (Exception ex) { _logger.LogError(ex.Message); } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var cnInfo = new ConnectionInfo(new Host("nats.cloudapp.net")) { AutoReconnectOnFailure = true, AutoRespondToPing = true, RequestTimeoutMs = (int)TimeSpan.FromMinutes(5).TotalMilliseconds }; var client = new NatsClient("request-response", cnInfo); client.Connect(); services.AddSingleton <INatsClient>(client); services.AddMvc(); }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample1", cnInfo)) { client.Connect(); //Subscribe using handler (action) await client.SubWithHandlerAsync( "demo", msg => Console.WriteLine(msg.GetPayloadAsString())); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample3", cnInfo)) { client.Connect(); //Subscribe with observer await client.SubWithObserverAsync( "demo", new DelegatingObserver <MsgOp>( msg => Console.WriteLine(msg.GetPayloadAsString()))); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample2", cnInfo)) { client.Connect(); //Subsribe and unsub after 3 messages var subInfo = new SubscriptionInfo("demo", maxMessages: 3); await client.SubWithHandlerAsync( subInfo, msg => Console.WriteLine(msg.GetPayloadAsString())); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public void IsMessageReceivedAfterLoggingIsDone() { var config = new NatsConfiguration { Host = "localhost", Port = 4222, ClientId = "Serilog.Sinks.Nats.IntegrationTests.Publisher", Subject = "IntegrationTest.TestSubject", RequestTimeoutMs = 1000, AutoReconnectOnFailure = true, AutoRespondToPing = true, BatchPostingLimit = 1, Credentials = new Credentials("test", "test"), Period = TimeSpan.FromMilliseconds(100), PubFlushMode = PubFlushMode.Auto, SocketOptions = new SocketOptions { ConnectTimeoutMs = 1000, ReceiveBufferSize = 50000, ReceiveTimeoutMs = 5000, SendBufferSize = 50000, SendTimeoutMs = 5000 }, Verbose = false }; Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.Nats(config, new JsonFormatter()) .CreateLogger(); var cnInfo = new ConnectionInfo("localhost") { Credentials = new Credentials("test", "test"), RequestTimeoutMs = 30000 }; var client = new NatsClient("Serilog.Sinks.Nats.IntegrationTests.Subscriber", cnInfo); client.Connect(); var foundMessage = false; client.SubWithHandlerAsync(config.Subject, msg => { foundMessage = true; }).ConfigureAwait(false); Log.Debug("Test message"); Thread.Sleep(1000); client.Disconnect(); Assert.True(foundMessage, "No log message received within timeout period"); }
public async Task Client_Should_not_reconnect_after_failure_When_not_configured_to_do_so() { const string subject = "test"; var wasDisconnectedDueToFailure = false; var wasReconnected = false; var ex = new Exception("This will destroy things."); var throwingLogger = new Mock <ILogger>(); throwingLogger.Setup(f => f.Error(It.Is <string>(m => m == "Error in observer while emitting value."), It.IsAny <Exception>())).Throws(ex); LoggerManager.Resolve = type => throwingLogger.Object; _client = new NatsClient(_cnInfoWithNoAutoReconnect); _client.Connect(); await _client.SubAsync(subject); _client.Events.OfType <ClientDisconnected>() .Where(ev => ev.Reason == DisconnectReason.DueToFailure) .Subscribe(ev => { wasDisconnectedDueToFailure = true; ReleaseOne(); }); _client.Events.OfType <ClientConnected>() .Subscribe(ev => { wasReconnected = true; ReleaseOne(); }); _client.MsgOpStream.Subscribe(msg => throw new Exception("Fail")); await _client.PubAsync(subject, "This message will fail"); //Wait for the Disconnected release and the potential Connected release WaitOne(); WaitOne(); wasDisconnectedDueToFailure.Should().BeTrue(); wasReconnected.Should().BeFalse(); _client.IsConnected.Should().BeFalse(); }
protected override async Task DoWork(PairConfig pair, CancellationToken stoppingToken) { _logger.LogInformation($"{Exchange.Description} Candles worker is started"); IPeriodCode candlePeriod = pair.Timeframe.HasValue ? PeriodCode.Create(pair.Timeframe.Value) : DefaultCandleInterval; while (!stoppingToken.IsCancellationRequested) { try { using (BinanceSocketClient client = new BinanceSocketClient()) { ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString); using (NatsClient natsClient = new NatsClient(cnInfo)) { if (!natsClient.IsConnected) { natsClient.Connect(); } CallResult <UpdateSubscription> successKline = client.SubscribeToKlineUpdates(pair.Symbol, candlePeriod.ToPeriodCode(), async(data) => { await SaveCandle(data.Data, natsClient); }); successKline.Data.ConnectionLost += () => { _logger.LogError($"Connection to {Exchange} is lost"); }; successKline.Data.ConnectionRestored += (data) => { _logger.LogError($"Connection to {Exchange} is Restored"); }; while (!stoppingToken.IsCancellationRequested) { } natsClient.Disconnect(); await client.Unsubscribe(successKline.Data); } } } catch (Exception ex) { _logger.LogError($"{Exchange.Description} Candles service failed with message: {ex.Message}", ex); } } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample9", cnInfo)) { client.Connect(); //Setup wildcard sub await client.SubWithHandlerAsync( "demo.>", msgOp => Console.WriteLine($"(1): {msgOp.Subject}:{msgOp.GetPayloadAsString()}")); await client.SubWithHandlerAsync( "demo.*", msgOp => Console.WriteLine($"(2): {msgOp.Subject}:{msgOp.GetPayloadAsString()}")); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public static async Task RunAsync(ConnectionInfo cnInfo) { var n = 0; using (var client = new NatsClient("Sample1", cnInfo)) { client.Connect(); //Subscribe using handler (action) await client.SubWithHandlerAsync( "demo", msg => n++); Console.WriteLine("Hit key to show num of received messages."); Console.ReadKey(); } Console.WriteLine(n); Console.ReadKey(); }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample6", cnInfo)) { client.Connect(); //Queue groups (start two or more consumers) //Queue groups means balancing as only one in the //group will get it. //NOTE! Others consumers on the same subject will also //get the message. var subInfo = new SubscriptionInfo("demo", queueGroup: "Grp1"); await client.SubWithHandlerAsync( subInfo, msgOp => Console.WriteLine(msgOp.GetPayloadAsString())); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample1", cnInfo)) { client.Connect(); //Consume JSON await client.SubWithHandlerAsync( "demo.greeting", msg => { var greeting = msg.FromJson <Greeting>(); Console.WriteLine($"{greeting.SentBy} said: {greeting.Message}"); }); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample5", cnInfo)) { client.Connect(); //RX using e.g. Transform, Filter and Sampling //Select messages that are longer than 3 and pick //the last known each 5th second await client.SubWithObservableSubscriptionAsync( "demo", msgOps => msgOps .Select(msgOp => msgOp.GetPayloadAsString()) .Where(msg => msg.Length > 3) .Sample(TimeSpan.FromSeconds(5)) .Subscribe(Console.WriteLine)); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Requester", cnInfo)) { client.Connect(); while (true) { Console.WriteLine("Request what? (blank=quit)"); var message = Console.ReadLine(); if (string.IsNullOrWhiteSpace(message)) { break; } var response = await client.RequestAsync("demo-request", message); Console.WriteLine($"Response: {response.GetPayloadAsString()}"); } } }
static async Task Main(string[] args) { Console.WriteLine("Hello World!"); // hit ctrl-C to close/exit var cts = new CancellationTokenSource(); Console.CancelKeyPress += (_, e) => { Console.WriteLine("cancelled..."); cts.Cancel(); e.Cancel = true; }; var sp = ConfigureServices(); var nats = new NatsClient(); await nats.StartAsync(new IPEndPoint(IPAddress.Loopback, 4222), sp); nats.Connect(new ConnectOperation { Verbose = false }); nats.Subscribe("test", msg => { var text = Encoding.UTF8.GetString(msg.Data.Span); Console.WriteLine($"OnMsg: subject:{msg.Subject} sid:{msg.Sid} replyto:{msg.ReplyTo} text:{text}"); }); while (!cts.Token.IsCancellationRequested) { Console.WriteLine("pub..."); nats.Publish("test", Encoding.UTF8.GetBytes("hello")); await Task.Delay(2000); } Console.WriteLine("done..."); Console.ReadLine(); }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample7", cnInfo)) { client.Connect(); //Respond to request's "replyTo" await client.SubWithHandlerAsync( "demo-request", msgOp => { var msg = msgOp.GetPayloadAsString(); Console.WriteLine($"I got request: {msg}"); client.Pub(msgOp.ReplyTo, $"You requested: {msg}"); }); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public async Task Client_Should_not_reconnect_When_user_initiated_disconnect() { const string subject = "test"; var wasDisconnectedDueToFailure = false; var wasDisconnected = false; var wasReconnected = false; _client = new NatsClient(_cnInfoWithAutoReconnect); _client.Connect(); await _client.SubAsync(subject); _client.Events.OfType <ClientDisconnected>() .Subscribe(ev => { wasDisconnectedDueToFailure = ev.Reason == DisconnectReason.DueToFailure; wasDisconnected = true; ReleaseOne(); }); _client.Events.OfType <ClientConnected>() .Subscribe(ev => { wasReconnected = true; ReleaseOne(); }); _client.Disconnect(); //Wait for the Disconnected release and the potentiall Connected release WaitOne(); WaitOne(); wasDisconnectedDueToFailure.Should().BeFalse(); wasDisconnected.Should().BeTrue(); wasReconnected.Should().BeFalse(); _client.IsConnected.Should().BeFalse(); }