private void InitChannel()
        {
            if (_channel != null)
            {
                return;
            }

            lock (_mutex)
            {
                if (_channel == null)
                {
                    _channel = _connection.CreateChannel();
                }
            }
        }
Esempio n. 2
0
        //TODO: BasicReturnEventHandler
        //TODO: channel и многопоточность - как не создавать каждый раз channel?
        public async Task PublishAsync <T>(Exchange exchange, string routingKey, T message,
                                           Dictionary <string, string> headers = null)
        {
            var span = _tracer.BuildSpan(nameof(PublishAsync)).Start();

            span.SetTag(nameof(message), JsonConvert.SerializeObject(message));

            try
            {
                using (var channel = _connection.CreateChannel())
                {
                    channel.ExchangeDeclare(exchange.Name, exchange.Type, exchange.IsDurable);

                    var properties = channel.CreateBasicProperties();
                    properties.ContentType  = "application/json";
                    properties.DeliveryMode = 2;
                    properties.Persistent   = true;

                    _tracer.Inject(_tracer.ActiveSpan.Context, BuiltinFormats.HttpHeaders,
                                   new HttpHeadersCarrier(properties.Headers));

                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            properties.Headers.Add(header.Key, header.Value);
                        }
                    }

                    var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));

                    channel.BasicPublish(exchange.Name, routingKey, true, properties, body);
                }
            }
            finally
            {
                span.Finish();
            }
        }