Ejemplo n.º 1
0
        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);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        /// <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>();
        }
Ejemplo n.º 3
0
        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");
        }
Ejemplo n.º 4
0
        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));
                    }
                }
            }
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        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);
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await WrapStarter(() => _connection = _connectionFactory.Get <QueryNatsAdapter>(), cancellationToken);

            var queue = _queueFactory.Get();

            _subscription = _connection.SubscribeAsync(queue, CreateHandler());
        }
Ejemplo n.º 8
0
 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>();
 }
Ejemplo n.º 9
0
        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); });
            }
        }
Ejemplo n.º 10
0
 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) => {}); });
         }
     }
 }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
 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) => {}); });
         }
     }
 }
Ejemplo n.º 13
0
        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;
        }
Ejemplo n.º 14
0
        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());
        }
Ejemplo n.º 16
0
        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);
            }
        }
Ejemplo n.º 17
0
        /// <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}");
            }
        }
Ejemplo n.º 18
0
        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));
                    }
                }
            }
        }
Ejemplo n.º 19
0
        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);
                                }
                            });
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        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);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        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);
        }
Ejemplo n.º 22
0
 public NatsClient(Options options)
 {
     _connection = CreateNatsConnection(options);
 }
Ejemplo n.º 23
0
 public NatsClient()
 {
     _connection = CreateNatsConnection(null);
 }
 public JsonEncodedNatsConnection(IEncodedConnection encodedConnection)
 {
     this.encodedConnection = encodedConnection;
 }
Ejemplo n.º 25
0
 /// <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;
 }
Ejemplo n.º 26
0
 public Worker(ILogger <Worker> logger)
 {
     _logger     = logger;
     _connection = NatsConnectionHelper.BuildConnection();
 }
Ejemplo n.º 27
0
        /// <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());
        }