public void TestEncodedSerizationOverrides() { using (new NATSServer()) { using (IEncodedConnection c = DefaultEncodedConnection) { c.OnDeserialize = jsonDeserializer; c.OnSerialize = jsonSerializer; AutoResetEvent ev = new AutoResetEvent(false); JsonObject origObj = new JsonObject("bar"); EventHandler <EncodedMessageEventArgs> eh = (sender, args) => { JsonObject so = (JsonObject)args.ReceivedObject; Assert.True(so.Equals(origObj)); ev.Set(); }; using (IAsyncSubscription s = c.SubscribeAsync("foo", eh)) { c.Publish("foo", origObj); c.Flush(); ev.WaitOne(1000); } } } }
/// <summary> /// Initializes a new instance of the <see cref="Publisher" /> class. /// </summary> /// <param name="connection">The connection.</param> /// <param name="subject">The subject.</param> public Subscriber(IEncodedConnection connection, string subject) { _connection = connection; _subject = subject; ReceivedUserMessages = new ConcurrentBag <UserMessage>(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { if (!_settings.Enabled) { return; } LogInfo("Starting.."); _connection = _connectionFactory.Get <BkMqMessage>(); WebDriver = DriverFactory.GetNewDriver(_settings.Driver); WebDriver.Open(_settings.Url, _waitBy); var sw = new Stopwatch(); sw.Start(); while (!stoppingToken.IsCancellationRequested) { var games = await FetchGames(); if (!games.Any()) { continue; } SendResult(new BkMqMessage(games)); Console.WriteLine($"{_settings.Url}: {sw.ElapsedMilliseconds}"); sw.Restart(); } LogInfo("Started"); }
public void TestEncodedObjectRequestReply() { using (new NATSServer()) { using (IEncodedConnection c = DefaultEncodedConnection) { c.OnDeserialize = jsonDeserializer; c.OnSerialize = jsonSerializer; JsonObject origObj = new JsonObject("foo"); EventHandler <EncodedMessageEventArgs> eh = (sender, args) => { JsonObject so = (JsonObject)args.ReceivedObject; Assert.True(so.Equals(origObj)); c.Publish(args.Reply, new JsonObject("Received")); c.Flush(); }; using (IAsyncSubscription s = c.SubscribeAsync("foo", eh)) { var jo = (JsonObject)c.Request("foo", origObj, 1000); Assert.True("Received".Equals(jo.Value)); jo = (JsonObject)c.Request("foo", origObj, 1000); Assert.True("Received".Equals(jo.Value)); } } } }
private Task <QueryNatsAdapter> GetResponse(IEncodedConnection connection, string replySubj, out IAsyncSubscription subscription) { var promise = new TaskCompletionSource <QueryNatsAdapter>(); var completed = 0; var waitTime = 0; ThreadPool.QueueUserWorkItem(data => { while (completed == 0) { if (waitTime >= 60) { promise.SetException(new Exception("Nats connection timeout exceed")); break; } Thread.Sleep(1000); waitTime++; } }); subscription = connection.SubscribeAsync(replySubj, (sender, args) => { var result = (QueryNatsAdapter)args.ReceivedObject; promise.SetResult(result); completed++; }); return(promise.Task); }
public void TestDefaultObjectSerialization() { using (new NATSServer()) { using (IEncodedConnection c = DefaultEncodedConnection) { Object mu = new Object(); SerializationTestObj origObj = new SerializationTestObj(); EventHandler <EncodedMessageEventArgs> eh = (sender, args) => { // Ensure we blow up in the cast SerializationTestObj so = (SerializationTestObj)args.ReceivedObject; Assert.True(so.Equals(origObj)); lock (mu) { Monitor.Pulse(mu); } }; using (IAsyncSubscription s = c.SubscribeAsync("foo", eh)) { lock (mu) { c.Publish("foo", new SerializationTestObj()); c.Flush(); Monitor.Wait(mu, 1000); } } } } }
public async Task StartAsync(CancellationToken cancellationToken) { await WrapStarter(() => _connection = _connectionFactory.Get <QueryNatsAdapter>(), cancellationToken); var queue = _queueFactory.Get(); _subscription = _connection.SubscribeAsync(queue, CreateHandler()); }
public NatsMessageBus(IDiScope diScope, INatsConnectionFactory connectionFactory, IRepository <IMessageResult> storage, INatsReceiverCommandQueueFactory queueFactory) { _diScope = diScope; _storage = storage; _queueFactory = queueFactory; _connection = connectionFactory.Get <CommandNatsAdapter>(); _responseConnection = connectionFactory.Get <ResultAdapter>(); }
public void Receive <T>(string subject, IMessageHandler <T> handler) where T : class { CommonConsumer <T> consumer = new CommonConsumer <T>(handler); using (IEncodedConnection connector = _natsConnectorFactory.GetConnector(defaultNatsURL)) { IAsyncSubscription s = connector.SubscribeAsync(subject, (sender, args) => { consumer.Process(args); }); } }
public void TestDefaultObjectSerialization() { using (NATSServer.CreateFastAndVerify(Context.Server1.Port)) { using (IEncodedConnection c = DefaultEncodedConnection) { Assert.Throws <NATSException>(() => { c.Publish("foo", new Object()); }); Assert.Throws <NATSException>(() => { c.SubscribeAsync("foo", (obj, args) => {}); }); } } }
private IEncodedConnection CreateNatsConnection(Options options) { ConnectionFactory cf = new ConnectionFactory(); IEncodedConnection conn = options != null?cf.CreateEncodedConnection(options) : cf.CreateEncodedConnection(); conn.OnDeserialize = JsonDeserializer; conn.OnSerialize = JsonSerializer; return(conn); }
public void TestDefaultObjectSerialization() { using (new NATSServer()) { using (IEncodedConnection c = DefaultEncodedConnection) { Assert.Throws <NATSException>(() => { c.Publish("foo", new Object()); }); Assert.Throws <NATSException>(() => { c.SubscribeAsync("foo", (obj, args) => {}); }); } } }
public DataSender(string subjectString, ILogger logger) { _subjectString = subjectString; _logger = logger; var options = ConnectionFactory.GetDefaultOptions(); options.AllowReconnect = true; options.MaxReconnect = Options.ReconnectForever; _connection = new ConnectionFactory().CreateEncodedConnection(options); _connection.OnSerialize = JsonSerializer <T> .Serialize; }
void sendAndCheckMsgs(IEncodedConnection ec, string subject, int numToSend) { for (int i = 0; i < numToSend; i++) { ec.Publish(subject, new NumberObj(i)); } ec.Flush(); Thread.Sleep(500); checkResults(numToSend); }
public async Task StartAsync(CancellationToken cancellationToken) { await WrapStarter(() => { _connection = _connectionFactory.Get <CommandNatsAdapter>(); _responeConnection = _connectionFactory.Get <ResultAdapter>(); }, cancellationToken); var commandQueue = _queueFactory.Get(); _subscription = _connection.SubscribeAsync(commandQueue.Key, commandQueue.Value, CreateHandler()); }
public bool Publish <T>(string subject, T message) where T : class { try { using (IEncodedConnection connector = _natsConnectorFactory.GetConnector(defaultNatsURL)) { connector.Publish(subject, message); } return(true); } catch { return(false); } }
/// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">The arguments.</param> static void Main(string[] args) { System.Console.WriteLine("Welcome to ChatClient!!!"); // User Identity System.Console.WriteLine("Please enter your name:"); var user = System.Console.ReadLine(); System.Console.WriteLine($"Hello {user} to ChatClient!"); ConfigurationBootstraper.InitUser(user); try { using (_connection = NatsConnectionFactory.ConnectToNats(string.IsNullOrWhiteSpace(ConfigurationBootstraper.AppConfig.NATSServerUrl) ? Defaults.Url : ConfigurationBootstraper.AppConfig.NATSServerUrl)) { // Initializes publisher and subscriber _publisher = new Publisher(_connection, ConfigurationBootstraper.AppConfig.NATSSubject); _subscriber = new Subscriber(_connection, ConfigurationBootstraper.AppConfig.NATSSubject); // Subscribe to the Subject SubscribeOnSubject(); System.Console.WriteLine("Continuous pub/sub chat"); System.Console.WriteLine("======================="); System.Console.WriteLine("Start chatting. Enter 'stop' to stopping the ChatClient."); while (isChattingContinue) { // Continous publish PublishOnSubject(); } // Unsubscribe the client _subscriber?.UnSubscribe(); System.Console.WriteLine("ChatClient stopped."); } } catch (Exception ex) { System.Console.WriteLine($"Unhandled exception occurred: {ex.Message}"); } }
public void TestEncodedObjectSerization() { using (new NATSServer()) { using (IEncodedConnection c = DefaultEncodedConnection) { c.OnDeserialize = jsonDeserializer; c.OnSerialize = jsonSerializer; AutoResetEvent ev = new AutoResetEvent(false); JsonObject jo = new JsonObject("bar"); EventHandler <EncodedMessageEventArgs> eh = (sender, args) => { Assert.True(args.ReceivedObject.Equals(jo)); ev.Set(); }; using (IAsyncSubscription s = c.SubscribeAsync("foo", eh)) { for (int i = 0; i < 10; i++) { c.Publish("foo", jo); } c.Flush(); Assert.True(ev.WaitOne(1000)); } ev.Reset(); using (IAsyncSubscription s = c.SubscribeAsync("foo", eh)) { c.Publish("foo", "bar", jo); c.Flush(); Assert.True(ev.WaitOne(1000)); } } } }
public void TestEncodedDefaultRequestReplyThreadSafety() { using (NATSServer.CreateFastAndVerify(Context.Server1.Port)) { using (IEncodedConnection c = DefaultEncodedConnection) { using (c.SubscribeAsync("replier", (obj, args) => { try { c.Publish(args.Reply, new BasicObj(((BasicObj) args.ReceivedObject).A)); } catch (Exception ex) { Assert.True(false, "Replier Exception: " + ex.Message); } c.Flush(); })) { c.Flush(); using (IEncodedConnection c2 = DefaultEncodedConnection) { System.Threading.Tasks.Parallel.For(0, 20, i => { try { var bo = new BasicObj(i); Assert.True(bo.Equals(c2.Request("replier", bo, 30000)), "Objects did not equal"); } catch (Exception ex) { Assert.True(false, "Exception: " + ex.Message); } }); } } } } }
public void TestEncodedInvalidObjectSerialization() { using (new NATSServer()) { using (IEncodedConnection c = DefaultEncodedConnection) { AutoResetEvent ev = new AutoResetEvent(false); c.OnSerialize = jsonSerializer; c.OnDeserialize = jsonSerializer; bool hitException = false; EventHandler <EncodedMessageEventArgs> eh = (sender, args) => { // Ensure we blow up in the cast or not implemented in .NET core try { Exception invalid = (Exception)args.ReceivedObject; } catch (Exception) { hitException = true; } ev.Set(); }; using (IAsyncSubscription s = c.SubscribeAsync("foo", eh)) { c.Publish("foo", new JsonObject("data")); c.Flush(); ev.WaitOne(1000); Assert.True(hitException); } } } }
void sendAndCheckMsgs(IEncodedConnection ec, string subject, int numToSend) { for (int i = 0; i < numToSend; i++) { ec.Publish(subject, new NumberObj(i)); } ec.Flush(); Thread.Sleep(500); checkResults(numToSend); }
public NatsClient(Options options) { _connection = CreateNatsConnection(options); }
public NatsClient() { _connection = CreateNatsConnection(null); }
public JsonEncodedNatsConnection(IEncodedConnection encodedConnection) { this.encodedConnection = encodedConnection; }
/// <summary> /// Initializes a new instance of the <see cref="Publisher" /> class. /// </summary> /// <param name="connection">The connection.</param> /// <param name="subject">The subject.</param> public Publisher(IEncodedConnection connection, string subject) { _connection = connection; _subject = subject; }
public Worker(ILogger <Worker> logger) { _logger = logger; _connection = NatsConnectionHelper.BuildConnection(); }
/// <summary> /// Start /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task StartAsync(CancellationToken cancellationToken) { await WrapStarter(() => _connection = _connectionFactory.Get <BkMqMessage>(), cancellationToken); _subscription = _connection.SubscribeAsync(_options.QueueSubject, CreateHandler()); }