Exemplo n.º 1
0
    public async Task PublishMessageAsync(MotorCloudEvent <byte[]> motorCloudEvent, CancellationToken token = default)
    {
        if (!_connected)
        {
            await StartAsync().ConfigureAwait(false);
        }

        if (_channel is null)
        {
            throw new InvalidOperationException("Channel is not created.");
        }

        var properties = _channel.CreateBasicProperties();

        properties.DeliveryMode = 2;
        properties.SetPriority(motorCloudEvent, _options);

        var exchange   = motorCloudEvent.GetRabbitMQExchange() ?? _options.PublishingTarget.Exchange;
        var routingKey = motorCloudEvent.GetRabbitMQRoutingKey() ?? _options.PublishingTarget.RoutingKey;

        if (_options.OverwriteExchange)
        {
            exchange = _options.PublishingTarget.Exchange;
        }

        switch (_publisherOptions.CloudEventFormat)
        {
        case CloudEventFormat.Protocol:
            properties.WriteCloudEventIntoHeader(motorCloudEvent);
            _channel.BasicPublish(exchange, routingKey, true, properties, motorCloudEvent.TypedData);
            break;

        case CloudEventFormat.Json:
            var data = _cloudEventFormatter.EncodeStructuredModeMessage(motorCloudEvent.ConvertToCloudEvent(), out _);
            _channel.BasicPublish(exchange, routingKey, true, properties, data);
            break;

        default:
            throw new UnhandledCloudEventFormatException(_publisherOptions.CloudEventFormat);
        }
    }