示例#1
0
        public void Subscribe()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            _consumerConnection = factory.CreateConnection();
            _consumerChannel    = _consumerConnection.CreateModel();
            _consumerChannel.QueueDeclare(queue: _configuration["ReceiveQueue"],
                                          durable: false,
                                          exclusive: false,
                                          autoDelete: false,
                                          arguments: null);

            var consumer = new EventingBasicConsumer(_consumerChannel);

            consumer.Received += async(model, ea) =>
            {
                var body = ea.Body;
                // Get our json event data
                var json = Encoding.UTF8.GetString(body);
                // Print data to debug
                Log.Debug($"Received message: [{json}].");
                // Deserialize json
                var eventData = JsonSerializer.Deserialize <SampleEvent>(json);
                // Notify SignalR clients
                await _hubContext.SendLogAsync($"Event received from [{eventData.From}] at [{eventData.Timestamp}] with content [{eventData.Description}].");
            };
            _consumerChannel.BasicConsume(queue: _configuration["ReceiveQueue"],
                                          autoAck: true,
                                          consumer: consumer);
        }