Path: redb-route/redb.Route.RabbitMQ/Fluent/Rabbit.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.RabbitMQ/Fluent/Rabbit.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
namespace redb.Route.RabbitMQ;
///
/// Fluent API for RabbitMQ endpoints.
///
/// .From(Rabbit.Queue("orders").Host("broker1").Exchange("exchange", "topic").RoutingKey("order.*"))
/// .To(Rabbit.Queue("notifications").Host("broker1").Declare())
///
///
public static class Rabbit
{
/// Creates a RabbitMQ endpoint for the given queue name.
public static RabbitBuilder Queue(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException(
"A queue name is required. For an endpoint on an exchange without a queue name (a producer that publishes "
+ "to the exchange, a consumer on a temporary queue of its own) use Rabbit.Exchange(name, type).",
nameof(name));
return new RabbitBuilder(name);
}
///
/// Creates a RabbitMQ endpoint on an exchange, without a queue name (rabbitmq:?exchange=...). A producer
/// publishes to the exchange with the routing key. A consumer reads a temporary queue of its own (exclusive,
/// auto-delete) that the broker names and that is bound to the exchange, so every consumer of a fanout exchange
/// gets its copy of each message; it needs , and fails at start without it.
///
/// Exchange name (template string, supports ${...}).
/// Exchange type: direct, topic, fanout or headers.
public static RabbitBuilder Exchange(string name, string? type = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return new RabbitBuilder(string.Empty).Exchange(name, type);
}
}
///
/// Fluent builder for RabbitMQ endpoint URIs.
///
public sealed class RabbitBuilder
{
private readonly string _queue;
// Connection
private string? _host;
private string? _port;
private string? _username;
private string? _password;
private string? _virtualHost;
private string? _connectionFactory;
private string? _clientName;
// Exchange
private string? _exchange;
private string? _exchangeType;
private bool? _exchangeDurable;
private bool? _exchangeAutoDelete;
private bool _declare;
// Queue
private bool? _durable;
private bool _autoDelete;
private bool _exclusive;
private string? _routingKey;
// Message
private string? _contentType;
private string? _messageTtl;
private string? _expires;
// Consumer
private string? _concurrentConsumers;
private string? _prefetchCount;
private AckMode? _ackMode;
private int? _maximumRetryAttempts;
private int? _retryDelay;
private bool? _rejectAndDontRequeue;
private bool _disableReplyTo;
private bool _batching;
private int? _maxBatchMessages;
private int? _pollTimeoutMs;
private int? _batchingIntervalMs;
private bool? _transacted;
private bool? _mandatory;
private bool _publisherConnection;
private bool _replyTo;
private bool _preserveMessageQos;
private string? _timeout;
private string? _confirmTimeout;
// Queue limits
private string? _maxLength;
private string? _maxLengthBytes;
private string? _overflow;
private string? _deadLetterExchange;
private string? _deadLetterRoutingKey;
private string? _queueType;
private string? _maxPriority;
// Connection settings
private bool? _automaticRecovery;
private bool? _topologyRecoveryEnabled;
private string? _recoveryInterval;
private string? _heartbeat;
private string? _connectionTimeout;
private string? _socketReadTimeout;
private string? _socketWriteTimeout;
private string? _continuationTimeout;
private string? _consumerDispatchConcurrency;
// SSL
private bool _ssl;
private string? _sslServerName;
private string? _sslCertPath;
private string? _sslCertPassword;
private string? _sslCaCertPath;
private System.Security.Authentication.SslProtocols _sslProtocols;
private System.Security.Cryptography.X509Certificates.X509RevocationMode _revocationMode;
private bool _revocationSoftFail;
private RabbitMQAuthMechanism _authMechanism;
// The entry points check the name: Rabbit.Queue requires one, Rabbit.Exchange passes none.
internal RabbitBuilder(string queue) => _queue = queue;
// ── Connection ────────────────────────────────────────────────────
/// Broker hostname. Default "localhost".
public RabbitBuilder Host(IExpression host) { _host = host.ToTemplateString(); return this; }
/// Broker hostname (template string, supports ${...}). Default "localhost".
public RabbitBuilder Host(string host) { _host = host; return this; }
/// Broker port. Default 5672.
public RabbitBuilder Port(int port) { _port = port.ToString(); return this; }
/// Broker port from an expression.
public RabbitBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; }
/// Username. Default "guest".
public RabbitBuilder Username(IExpression username) { _username = username.ToTemplateString(); return this; }
/// Username (template string, supports ${...}). Default "guest".
public RabbitBuilder Username(string username) { _username = username; return this; }
/// Password. Default "guest".
public RabbitBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; }
/// Password (template string, supports ${...}). Default "guest".
public RabbitBuilder Password(string password) { _password = password; return this; }
/// Virtual host. Default "/".
public RabbitBuilder VirtualHost(IExpression vhost) { _virtualHost = vhost.ToTemplateString(); return this; }
/// Virtual host (template string, supports ${...}). Default "/".
public RabbitBuilder VirtualHost(string vhost) { _virtualHost = vhost; return this; }
/// Use a named connection factory registered in DI.
public RabbitBuilder ConnectionFactory(IExpression name) { _connectionFactory = name.ToTemplateString(); return this; }
/// Use a named connection factory registered in DI (template string, supports ${...}).
public RabbitBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Client connection name. Default "redb.Route".
public RabbitBuilder ClientName(IExpression name) { _clientName = name.ToTemplateString(); return this; }
/// Client connection name (template string, supports ${...}). Default "redb.Route".
public RabbitBuilder ClientName(string name) { _clientName = name; return this; }
// ── Exchange ──────────────────────────────────────────────────────
/// Exchange name and optionally type (direct, topic, fanout, headers).
public RabbitBuilder Exchange(IExpression name, string? type = null)
{
_exchange = name.ToTemplateString(); if (type != null) _exchangeType = type; return this;
}
/// Exchange name (template string, supports ${...}) and optionally type.
public RabbitBuilder Exchange(string name, string? type = null)
{
_exchange = name; if (type != null) _exchangeType = type; return this;
}
/// Exchange durability. Default true.
public RabbitBuilder ExchangeDurable(bool durable = true) { _exchangeDurable = durable; return this; }
/// Exchange auto-delete when last consumer unsubscribes.
public RabbitBuilder ExchangeAutoDelete() { _exchangeAutoDelete = true; return this; }
/// Declare exchange and queue on startup.
public RabbitBuilder Declare() { _declare = true; return this; }
// ── Queue ─────────────────────────────────────────────────────────
/// Queue durability. Default true.
public RabbitBuilder Durable(bool durable = true) { _durable = durable; return this; }
/// Auto-delete queue.
public RabbitBuilder AutoDelete() { _autoDelete = true; return this; }
/// Exclusive queue (only this connection).
public RabbitBuilder Exclusive() { _exclusive = true; return this; }
/// Routing key for binding.
public RabbitBuilder RoutingKey(IExpression key) { _routingKey = key.ToTemplateString(); return this; }
/// Routing key (template string, supports ${...} for a per-message key).
public RabbitBuilder RoutingKey(string key) { _routingKey = key; return this; }
// ── Message ───────────────────────────────────────────────────────
/// Content type. Default "application/json".
public RabbitBuilder ContentType(string type) { _contentType = type; return this; }
/// Per-message TTL in milliseconds.
public RabbitBuilder MessageTtl(int ms) { _messageTtl = ms.ToString(); return this; }
/// Per-message TTL from an expression.
public RabbitBuilder MessageTtl(IExpression ms) { _messageTtl = ms.ToTemplateString(); return this; }
/// Queue expires (auto-delete) after ms of inactivity. 0 = never.
public RabbitBuilder Expires(int ms) { _expires = ms.ToString(); return this; }
/// Queue expiry from an expression.
public RabbitBuilder Expires(IExpression ms) { _expires = ms.ToTemplateString(); return this; }
// ── Consumer ──────────────────────────────────────────────────────
/// Number of concurrent consumers. Default 1.
public RabbitBuilder ConcurrentConsumers(int count) { _concurrentConsumers = count.ToString(); return this; }
/// Consumer parallelism as a string: a number or "auto" (= max(CPU, 2)).
public RabbitBuilder ConcurrentConsumers(string count) { _concurrentConsumers = count; return this; }
/// Concurrent consumers from an expression.
public RabbitBuilder ConcurrentConsumers(IExpression count) { _concurrentConsumers = count.ToTemplateString(); return this; }
/// Prefetch count. Default 10.
public RabbitBuilder PrefetchCount(ushort count) { _prefetchCount = count.ToString(); return this; }
/// Prefetch count from an expression.
public RabbitBuilder PrefetchCount(IExpression count) { _prefetchCount = count.ToTemplateString(); return this; }
///
/// When the delivery is settled. : the broker settles it on hand-off
/// (at-most-once), a failed turn does not requeue it. Default (at-least-once).
/// Auto cannot be combined with .
///
public RabbitBuilder AckMode(AckMode mode) { _ackMode = mode; return this; }
/// Attempts on a failed delivery, the first included (Apache Camel maximumRetryAttempts, default 5).
public RabbitBuilder MaximumRetryAttempts(int attempts) { _maximumRetryAttempts = attempts; return this; }
/// Milliseconds between two attempts on a failed delivery (Apache Camel retryDelay, default 1000).
public RabbitBuilder RetryDelay(int milliseconds) { _retryDelay = milliseconds; return this; }
///
/// Whether a delivery that failed every attempt is rejected without requeue, to the dead letter exchange (Apache Camel
/// rejectAndDontRequeue, default true), or requeued.
///
public RabbitBuilder RejectAndDontRequeue(bool value) { _rejectAndDontRequeue = value; return this; }
/// The consumer ignores a delivery's reply-to (Apache Camel disableReplyTo): no reply, and a batch takes it.
public RabbitBuilder DisableReplyTo() { _disableReplyTo = true; return this; }
/// Batch mode (batching=true): the route gets the deliveries as a List<IMessage>.
public RabbitBuilder Batching() { _batching = true; return this; }
/// Largest number of deliveries in a batch (maxBatchMessages, default and maximum prefetchCount).
public RabbitBuilder MaxBatchMessages(int max) { _maxBatchMessages = max; return this; }
/// Idle timeout of a batch in milliseconds (pollTimeoutMs, default 1000).
public RabbitBuilder PollTimeoutMs(int ms) { _pollTimeoutMs = ms; return this; }
/// Hard limit of a batch in milliseconds from its first delivery (batchingIntervalMs).
public RabbitBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms; return this; }
/// Enable transacted channel.
public RabbitBuilder Transacted() { _transacted = true; return this; }
///
/// Sets transacted explicitly. false sends at once even inside a .Transacted() block, outside its
/// transaction; left unset, a producer follows the block.
///
public RabbitBuilder Transacted(bool value) { _transacted = value; return this; }
/// Set mandatory flag on published messages.
public RabbitBuilder Mandatory() { _mandatory = true; return this; }
///
/// Publish over a connection of its own: this endpoint's sends and its consumer's RPC replies go over a second
/// connection with the same settings, so the broker blocking publishers cannot stop consumers from acking.
///
public RabbitBuilder PublisherConnection() { _publisherConnection = true; return this; }
/// Enable request-reply with temporary reply queue.
public RabbitBuilder ReplyTo() { _replyTo = true; return this; }
///
/// Keep the ReplyTo header as the reply-to of an ordinary send (Apache Camel preserveMessageQos); without it
/// a forwarded sender's reply-to is not carried on.
///
public RabbitBuilder PreserveMessageQos() { _preserveMessageQos = true; return this; }
/// Consumer/producer timeout in seconds. Default 60.
public RabbitBuilder Timeout(int seconds) { _timeout = seconds.ToString(); return this; }
/// Timeout from an expression.
public RabbitBuilder Timeout(IExpression seconds) { _timeout = seconds.ToTemplateString(); return this; }
///
/// How long a send may take until the broker has taken it, in milliseconds. Default 5000. A send to a broker that
/// blocks its publishers fails with when it expires.
///
public RabbitBuilder ConfirmTimeout(int milliseconds) { _confirmTimeout = milliseconds.ToString(); return this; }
/// Confirm timeout from an expression.
public RabbitBuilder ConfirmTimeout(IExpression milliseconds) { _confirmTimeout = milliseconds.ToTemplateString(); return this; }
// ── Queue limits ──────────────────────────────────────────────────
/// Max queue length (number of messages).
public RabbitBuilder MaxLength(int max) { _maxLength = max.ToString(); return this; }
/// Max queue length from an expression.
public RabbitBuilder MaxLength(IExpression max) { _maxLength = max.ToTemplateString(); return this; }
/// Max queue size in bytes.
public RabbitBuilder MaxLengthBytes(int max) { _maxLengthBytes = max.ToString(); return this; }
/// Max queue size from an expression.
public RabbitBuilder MaxLengthBytes(IExpression max) { _maxLengthBytes = max.ToTemplateString(); return this; }
/// Overflow strategy: "drop-head", "reject-publish", "reject-publish-dlx".
public RabbitBuilder Overflow(string policy) { _overflow = policy; return this; }
/// Dead letter exchange name.
public RabbitBuilder DeadLetterExchange(IExpression exchange) { _deadLetterExchange = exchange.ToTemplateString(); return this; }
/// Dead letter exchange name (template string, supports ${...}).
public RabbitBuilder DeadLetterExchange(string exchange) { _deadLetterExchange = exchange; return this; }
/// Dead letter routing key.
public RabbitBuilder DeadLetterRoutingKey(IExpression key) { _deadLetterRoutingKey = key.ToTemplateString(); return this; }
/// Dead letter routing key (template string, supports ${...}).
public RabbitBuilder DeadLetterRoutingKey(string key) { _deadLetterRoutingKey = key; return this; }
/// Queue type: "classic", "quorum", "stream".
public RabbitBuilder QueueType(string type) { _queueType = type; return this; }
/// Max priority level. Default 0 (disabled).
public RabbitBuilder MaxPriority(int priority) { _maxPriority = priority.ToString(); return this; }
/// Max priority from an expression.
public RabbitBuilder MaxPriority(IExpression priority) { _maxPriority = priority.ToTemplateString(); return this; }
// ── Connection settings ───────────────────────────────────────────
/// Enable automatic connection recovery. Default true.
public RabbitBuilder AutomaticRecovery(bool enabled = true) { _automaticRecovery = enabled; return this; }
/// Enable topology recovery. Default true.
public RabbitBuilder TopologyRecoveryEnabled(bool enabled = true) { _topologyRecoveryEnabled = enabled; return this; }
/// Recovery interval in seconds. Default 5.
public RabbitBuilder RecoveryInterval(int seconds) { _recoveryInterval = seconds.ToString(); return this; }
/// Recovery interval from an expression.
public RabbitBuilder RecoveryInterval(IExpression seconds) { _recoveryInterval = seconds.ToTemplateString(); return this; }
/// Heartbeat interval in seconds. Default 60.
public RabbitBuilder Heartbeat(int seconds) { _heartbeat = seconds.ToString(); return this; }
/// Heartbeat interval from an expression.
public RabbitBuilder Heartbeat(IExpression seconds) { _heartbeat = seconds.ToTemplateString(); return this; }
/// Connection timeout in seconds. Default 60.
public RabbitBuilder ConnectionTimeout(int seconds) { _connectionTimeout = seconds.ToString(); return this; }
/// Connection timeout from an expression.
public RabbitBuilder ConnectionTimeout(IExpression seconds) { _connectionTimeout = seconds.ToTemplateString(); return this; }
/// Socket read timeout in seconds. Default 30.
public RabbitBuilder SocketReadTimeout(int seconds) { _socketReadTimeout = seconds.ToString(); return this; }
/// Socket read timeout from an expression.
public RabbitBuilder SocketReadTimeout(IExpression seconds) { _socketReadTimeout = seconds.ToTemplateString(); return this; }
/// Socket write timeout in seconds. Default 30.
public RabbitBuilder SocketWriteTimeout(int seconds) { _socketWriteTimeout = seconds.ToString(); return this; }
/// Socket write timeout from an expression.
public RabbitBuilder SocketWriteTimeout(IExpression seconds) { _socketWriteTimeout = seconds.ToTemplateString(); return this; }
/// Continuation timeout in seconds. Default 30.
public RabbitBuilder ContinuationTimeout(int seconds) { _continuationTimeout = seconds.ToString(); return this; }
/// Continuation timeout from an expression.
public RabbitBuilder ContinuationTimeout(IExpression seconds) { _continuationTimeout = seconds.ToTemplateString(); return this; }
/// Consumer dispatch concurrency. Default 1.
public RabbitBuilder ConsumerDispatchConcurrency(ushort count) { _consumerDispatchConcurrency = count.ToString(); return this; }
/// Consumer dispatch concurrency from an expression.
public RabbitBuilder ConsumerDispatchConcurrency(IExpression count) { _consumerDispatchConcurrency = count.ToTemplateString(); return this; }
// ── SSL ───────────────────────────────────────────────────────────
/// Enable SSL with optional server name and client certificate.
public RabbitBuilder Ssl(IExpression? serverName = null, IExpression? certPath = null, IExpression? certPassphrase = null)
{
_ssl = true; _sslServerName = serverName?.ToTemplateString(); _sslCertPath = certPath?.ToTemplateString(); _sslCertPassword = certPassphrase?.ToTemplateString();
return this;
}
/// PEM file with the root certificates the broker certificate must chain to, instead of the system trust store.
public RabbitBuilder SslCaCertPath(IExpression path) { _sslCaCertPath = path.ToTemplateString(); return this; }
/// Allowed TLS versions: Tls12, Tls13 or both. Unset, the operating system chooses.
public RabbitBuilder SslProtocols(System.Security.Authentication.SslProtocols protocols) { _sslProtocols = protocols; return this; }
/// Revocation check of the broker certificate; accepts an undeterminable status.
public RabbitBuilder RevocationMode(System.Security.Cryptography.X509Certificates.X509RevocationMode mode, bool softFail = false)
{
_revocationMode = mode; _revocationSoftFail = softFail;
return this;
}
/// Log in with the TLS client certificate () instead of a password.
public RabbitBuilder AuthMechanism(RabbitMQAuthMechanism mechanism) { _authMechanism = mechanism; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the RabbitMQ endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("rabbitmq:");
sb.Append(_queue);
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value)
{
if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant());
}
// Connection
AppendIf("host", _host);
AppendIf("port", _port);
AppendIf("username", _username);
AppendIf("password", _password);
AppendIf("virtualHost", _virtualHost);
AppendIf("connectionFactory", _connectionFactory);
AppendIf("clientName", _clientName);
// Exchange
AppendIf("exchange", _exchange);
AppendIf("exchangeType", _exchangeType);
AppendBoolExplicit("exchangeDurable", _exchangeDurable);
AppendBoolExplicit("exchangeAutoDelete", _exchangeAutoDelete);
AppendBool("declare", _declare);
// Queue
AppendBoolExplicit("durable", _durable);
AppendBool("autoDelete", _autoDelete);
AppendBool("exclusive", _exclusive);
AppendIf("routingKey", _routingKey);
// Message
AppendIf("contentType", _contentType);
AppendIf("messageTtl", _messageTtl);
AppendIf("expires", _expires);
// Consumer
AppendIf("concurrentConsumers", _concurrentConsumers);
AppendIf("prefetchCount", _prefetchCount);
AppendIf("ackMode", _ackMode?.ToString().ToLowerInvariant());
AppendIf("maximumRetryAttempts", _maximumRetryAttempts?.ToString());
AppendIf("retryDelay", _retryDelay?.ToString());
AppendBoolExplicit("rejectAndDontRequeue", _rejectAndDontRequeue);
AppendBool("disableReplyTo", _disableReplyTo);
AppendBool("batching", _batching);
AppendIf("maxBatchMessages", _maxBatchMessages?.ToString());
AppendIf("pollTimeoutMs", _pollTimeoutMs?.ToString());
AppendIf("batchingIntervalMs", _batchingIntervalMs?.ToString());
if (_transacted is { } transacted) Append("transacted", transacted ? "true" : "false");
AppendBoolExplicit("mandatory", _mandatory);
AppendBool("replyTo", _replyTo);
AppendBool("preserveMessageQos", _preserveMessageQos);
AppendBool("publisherConnection", _publisherConnection);
AppendIf("timeout", _timeout);
AppendIf("confirmTimeout", _confirmTimeout);
// Queue limits
AppendIf("maxLength", _maxLength);
AppendIf("maxLengthBytes", _maxLengthBytes);
AppendIf("overflow", _overflow);
AppendIf("deadLetterExchange", _deadLetterExchange);
AppendIf("deadLetterRoutingKey", _deadLetterRoutingKey);
AppendIf("queueType", _queueType);
AppendIf("maxPriority", _maxPriority);
// Connection settings
AppendBoolExplicit("automaticRecovery", _automaticRecovery);
AppendBoolExplicit("topologyRecoveryEnabled", _topologyRecoveryEnabled);
AppendIf("recoveryInterval", _recoveryInterval);
AppendIf("heartbeat", _heartbeat);
AppendIf("connectionTimeout", _connectionTimeout);
AppendIf("socketReadTimeout", _socketReadTimeout);
AppendIf("socketWriteTimeout", _socketWriteTimeout);
AppendIf("continuationTimeout", _continuationTimeout);
AppendIf("consumerDispatchConcurrency", _consumerDispatchConcurrency);
// SSL
AppendBool("ssl", _ssl);
AppendIf("sslServerName", _sslServerName);
AppendIf("sslCertPath", _sslCertPath);
AppendIf("sslCertPassword", _sslCertPassword);
AppendIf("sslCaCertPath", _sslCaCertPath);
if (_sslProtocols != System.Security.Authentication.SslProtocols.None) Append("sslProtocols", _sslProtocols.ToString().Replace(" ", string.Empty));
if (_revocationMode != System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck) Append("revocationMode", _revocationMode.ToString());
AppendBool("revocationSoftFail", _revocationSoftFail);
if (_authMechanism != RabbitMQAuthMechanism.Plain) Append("authMechanism", _authMechanism.ToString());
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(RabbitBuilder b) => b.Build();
///
public override string ToString() => Build();
}