amqp

package module
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 24 Imported by: 6

README

go-messaging-amqp

AMQP/RabbitMQ transport for gomessaging -- opinionated event-driven messaging with deterministic topology, CloudEvents, and OpenTelemetry.

CI Go Reference


This package implements the gomessaging specification for AMQP 0-9-1 (RabbitMQ). It provides deterministic exchange/queue naming, CloudEvents 1.0 metadata, quorum queues with single active consumer by default, publisher confirms, and full OpenTelemetry tracing and Prometheus metrics.

Deep dives: See the docs/ directory for detailed guides on connection lifecycle, consumers, publishers, request-response, observability, and topology & naming.

Installation

go get codeberg.org/messaging/go-messaging-amqp

Requires Go 1.24+.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "codeberg.org/messaging/go-messaging-amqp"
    spec "codeberg.org/messaging/messaging"
)

type OrderCreated struct {
    OrderID string `json:"order_id"`
    Amount  int    `json:"amount"`
}

func main() {
    ctx := context.Background()

    conn, err := amqp.NewFromURL("order-service", "amqp://guest:guest@localhost:5672/")
    if err != nil {
        log.Fatal(err)
    }

    pub := amqp.NewPublisher()

    err = conn.Start(ctx,
        amqp.EventStreamPublisher(pub),
        amqp.EventStreamConsumer("Order.Created", func(ctx context.Context, e spec.ConsumableEvent[OrderCreated]) error {
            fmt.Printf("received order %s, amount %d\n", e.Payload.OrderID, e.Payload.Amount)
            return nil
        }),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    err = pub.Publish(ctx, "Order.Created", OrderCreated{OrderID: "abc-123", Amount: 42})
    if err != nil {
        log.Fatal(err)
    }
}

Messaging Patterns

Event Stream

Publish domain events to the shared events.topic.exchange. Any number of services subscribe by routing key. Durable consumers use quorum queues that survive restarts. Transient consumers auto-delete on disconnect.

pub := amqp.NewPublisher()

conn.Start(ctx,
    // Publisher
    amqp.EventStreamPublisher(pub),

    // Durable consumer (quorum queue, single active consumer)
    amqp.EventStreamConsumer("Order.Created", func(ctx context.Context, e spec.ConsumableEvent[OrderCreated]) error {
        return processOrder(e.Payload)
    }),

    // Transient consumer (auto-delete queue, ephemeral)
    amqp.TransientEventStreamConsumer("Order.*", func(ctx context.Context, e spec.ConsumableEvent[any]) error {
        log.Println("transient:", e.DeliveryInfo.Key)
        return nil
    }),
)

pub.Publish(ctx, "Order.Created", OrderCreated{OrderID: "abc-123", Amount: 42})
Custom Stream

Same as event stream but on a named exchange instead of the default events exchange. Use when events belong to a separate domain.

pub := amqp.NewPublisher()

conn.Start(ctx,
    amqp.StreamPublisher("audit", pub),
    amqp.StreamConsumer("audit", "User.Login", func(ctx context.Context, e spec.ConsumableEvent[UserLogin]) error {
        return recordAuditEntry(e.Payload)
    }),
)

pub.Publish(ctx, "User.Login", UserLogin{UserID: "u-42"})
Service Request-Response

Synchronous request-reply between services. The handler receives a request and returns a response that is automatically published back to the calling service.

// --- billing-service ---
billingConn.Start(ctx,
    amqp.RequestResponseHandler("Invoice.Create", func(ctx context.Context, e spec.ConsumableEvent[InvoiceRequest]) (InvoiceResponse, error) {
        invoice := createInvoice(e.Payload)
        return InvoiceResponse{InvoiceID: invoice.ID}, nil
    }),
)

// --- order-service (caller) ---
pub := amqp.NewPublisher()

orderConn.Start(ctx,
    amqp.ServicePublisher("billing-service", pub),
    amqp.ServiceResponseConsumer("billing-service", "Invoice.Create", func(ctx context.Context, e spec.ConsumableEvent[InvoiceResponse]) error {
        fmt.Println("invoice created:", e.Payload.InvoiceID)
        return nil
    }),
)

pub.Publish(ctx, "Invoice.Create", InvoiceRequest{OrderID: "abc-123"})
Queue Publish

Direct publish to a named queue using sender-selected distribution. The sender picks the destination queue. Useful for work queues and task distribution.

pub := amqp.NewPublisher()

conn.Start(ctx,
    amqp.QueuePublisher(pub, "email-tasks"),
)

pub.Publish(ctx, "", EmailTask{To: "user@example.com", Subject: "Hello"})

Configuration

Connection Options

Setup functions are passed to conn.Start() to configure the connection before consumers start.

Function Description
WithLogger(logger) Use a custom *slog.Logger. Defaults to slog.Default().
WithTracing(tp) Set a trace.TracerProvider. Defaults to otel.GetTracerProvider().
WithPropagator(p) Set a propagation.TextMapPropagator. Defaults to otel.GetTextMapPropagator().
WithPrefetchLimit(n) Number of messages to prefetch per consumer channel. Default: 20. Set to 1 for strict round-robin.
WithSpanNameFn(fn) Custom span name for consume operations. Receives spec.DeliveryInfo.
WithPublishSpanNameFn(fn) Custom span name for publish operations. Receives (exchange, routingKey).
WithLegacySupport() Enrich incoming messages that lack CloudEvents headers with synthetic metadata.
CloseListener(ch) Receive error values on channel/connection close events.
WithNotificationChannel(ch) Receive spec.Notification on successful event processing.
WithErrorChannel(ch) Receive spec.ErrorNotification on failed event processing.
Consumer Options

Passed as variadic arguments to consumer setup functions (e.g., EventStreamConsumer, StreamConsumer).

Function Description
AddQueueNameSuffix(suffix) Append a suffix to the queue name. Useful when multiple consumers in the same service subscribe to the same routing key.
DisableSingleActiveConsumer() Allow multiple active consumers on the queue (default is single active consumer).
WithDeadLetter(exchange...) Enable dead-lettering. No argument uses the managed per-service DLX/DLQ (auto-declared); pass an exchange name to use an existing external one.
WithDeadLetterRoutingKey(key) Set a custom routing key for dead-lettered messages.
Publisher Options

Passed to NewPublisher().

Function Description
WithConfirm(ch) Enable publisher confirms with a custom confirmation channel.
WithoutPublisherConfirms() Disable publisher confirms (enabled by default). Use for high-throughput scenarios where occasional message loss is acceptable.

Observability

Tracing

OpenTelemetry spans are created for every publish and consume operation with semantic convention attributes (messaging.system, messaging.operation, messaging.destination.name, messaging.rabbitmq.routing_key). Trace context propagates through AMQP message headers.

import (
    "go.opentelemetry.io/otel/propagation"
    sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

tp := sdktrace.NewTracerProvider(
    sdktrace.WithBatcher(exporter),
)

conn.Start(ctx,
    amqp.WithTracing(tp),
    amqp.WithPropagator(propagation.TraceContext{}),
    // ... publishers and consumers
)
Metrics

Register Prometheus metrics once at startup with InitMetrics.

import "github.com/prometheus/client_golang/prometheus"

err := amqp.InitMetrics(prometheus.DefaultRegisterer)

Use WithRoutingKeyMapper to normalize dynamic routing key segments and prevent unbounded label cardinality:

amqp.InitMetrics(prometheus.DefaultRegisterer, amqp.WithRoutingKeyMapper(func(key string) string {
    // Redact UUIDs from routing keys
    return uuidRegex.ReplaceAllString(key, "<id>")
}))
Metric Type Labels Description
amqp_events_received counter queue, routing_key Events received
amqp_events_ack counter queue, routing_key Events acknowledged
amqp_events_nack counter queue, routing_key Events rejected
amqp_events_without_handler counter queue, routing_key Events with no registered handler
amqp_events_not_parsable counter queue, routing_key Events that failed JSON parsing
amqp_events_processed_duration histogram queue, routing_key, result Processing time (ms)
amqp_events_publish_succeed counter exchange, routing_key Successful publishes
amqp_events_publish_failed counter exchange, routing_key Failed publishes
amqp_events_publish_duration histogram exchange, routing_key, result Publish time (ms)
Notifications

Monitor event processing outcomes through notification channels.

notifyCh := make(chan spec.Notification, 100)
errorCh := make(chan spec.ErrorNotification, 100)

conn.Start(ctx,
    amqp.WithNotificationChannel(notifyCh),
    amqp.WithErrorChannel(errorCh),
    // ... publishers and consumers
)

go func() {
    for n := range notifyCh {
        log.Printf("processed %s in %dms", n.DeliveryInfo.Key, n.Duration)
    }
}()

go func() {
    for e := range errorCh {
        log.Printf("failed %s: %v", e.DeliveryInfo.Key, e.Error)
    }
}()

Connection Lifecycle

Close Listener

Monitor unexpected disconnects using CloseListener. The channel receives errors from both AMQP channel and connection close events.

closeCh := make(chan error, 1)

conn.Start(ctx,
    amqp.CloseListener(closeCh),
    // ... publishers and consumers
)

go func() {
    if err := <-closeCh; err != nil {
        log.Printf("AMQP disconnected: %v", err)
        os.Exit(1)
    }
}()
Graceful Shutdown
conn.Close()

Topology Export

After Start(), the connection exposes the declared topology for validation and visualization using the spec module.

topology := conn.Topology()
// topology is a spec.Topology with Transport, ServiceName, and Endpoints

errors := spec.Validate(topology)
diagram := spec.Mermaid([]spec.Topology{topology})

Development

# Start RabbitMQ
docker compose up -d

# Run tests
go test ./...

# Lint
go vet ./...

TCK Adapter

The cmd/tck-adapter/ directory contains a Technology Compatibility Kit adapter that proves this transport conforms to the gomessaging specification. It implements the JSON-RPC subprocess protocol used by the TCK runner.

go build -o tck-adapter ./cmd/tck-adapter/

License

MIT

Documentation

Overview

Package amqp provides an opinionated RabbitMQ transport for event-driven architectures, built on the gomessaging spec module for naming conventions, topology, and CloudEvents support.

Index

Constants

View Source
const (
	DefaultReconnectInterval    = 1 * time.Second
	DefaultReconnectMaxInterval = 30 * time.Second
	DefaultReconnectMaxElapsed  = 2 * time.Minute
)

Defaults for WithReconnect, used for any option left unset.

Variables

View Source
var (
	// ErrEmptySuffix is returned when an empty suffix is passed to AddQueueNameSuffix.
	ErrEmptySuffix = fmt.Errorf("empty queue suffix not allowed")
	// ErrAlreadyStarted is returned when Start is called on an already-started connection.
	ErrAlreadyStarted = fmt.Errorf("already started")
)
View Source
var ErrEmptyHeaderKey = errors.New("empty key not allowed")

ErrEmptyHeaderKey is returned when a Header is created with an empty key.

View Source
var ErrNoMessageTypeForRouteKey = fmt.Errorf("no message type for routing key configured")

ErrNoMessageTypeForRouteKey is returned when a TypeMapper has no type registered for the routing key.

View Source
var ErrNotConnected = errors.New("amqp connection not established")

ErrNotConnected is returned when a publish is attempted while the connection is down, typically between a disconnect and a successful reconnect.

Functions

func CollectTopology

func CollectTopology(serviceName string, setups ...Setup) (spec.Topology, error)

CollectTopology runs the given setup functions against a no-op channel to collect the topology that would be declared, without connecting to a broker. This is useful for generating topology JSON for visualization or validation.

func InitMetrics

func InitMetrics(registerer prometheus.Registerer, opts ...MetricsOption) error

InitMetrics registers all AMQP Prometheus metrics with the given registerer. Call this once during application startup before Start(), e.g. InitMetrics(prometheus.DefaultRegisterer). The mapper is applied globally and subsequent calls overwrite the previous mapper.

func Must

func Must[T any](t *T, err error) *T

Must is a helper that wraps a call to a function returning (*T, error) and panics if the error is non-nil. It is intended for use in variable initializations such as var c = goamqp.Must(goamqp.NewFromURL("service", "amqp://"))

func TypeMappingHandler

func TypeMappingHandler(handler spec.EventHandler[any], routingKeyToType TypeMapper) spec.EventHandler[any]

TypeMappingHandler wraps an EventHandler[any] and uses the TypeMapper to unmarshal each message payload into the correct concrete type before passing it to the handler. This is useful when a single consumer handles multiple event types on a wildcard routing key.

Types

type Connection

type Connection struct {
	// contains filtered or unexported fields
}

Connection is a wrapper around the actual amqp.Connection and amqp.Channel

func NewFromURL

func NewFromURL(serviceName string, amqpURL string) (*Connection, error)

NewFromURL creates a new Connection by parsing an AMQP URL. The serviceName is used for exchange/queue naming and tracing.

func (*Connection) Close

func (c *Connection) Close() error

Close closes the amqp connection, see amqp.Connection.Close

func (*Connection) PublishServiceResponse

func (c *Connection) PublishServiceResponse(ctx context.Context, targetService, routingKey string, msg any) error

PublishServiceResponse sends a message to targetService as a handler response

func (*Connection) Start

func (c *Connection) Start(ctx context.Context, opts ...Setup) (err error)

Start connects to AMQP, applies each Setup function to declare exchanges, queues, and bindings, then starts all consumers. It returns ErrAlreadyStarted if called twice.

func (*Connection) Topology

func (c *Connection) Topology() spec.Topology

Topology returns the messaging topology declared by this connection's setup. It is populated during Start() as setup functions execute.

func (*Connection) URI

func (c *Connection) URI() amqp.URI

URI returns the parsed AMQP URI used by this connection.

type ConsumerOptions

type ConsumerOptions func(config *consumerConfig) error

ConsumerOptions is a setup function that takes a consumerConfig and provide custom changes to the configuration

func AddQueueNameSuffix

func AddQueueNameSuffix(suffix string) ConsumerOptions

AddQueueNameSuffix appends the provided suffix to the queue name Useful when multiple queueConsumers are needed for a routing key in the same service

func DisableSingleActiveConsumer

func DisableSingleActiveConsumer() ConsumerOptions

DisableSingleActiveConsumer will define the queue as non exclusive and set the x-single-active-consumer header to false https://www.rabbitmq.com/docs/consumers#exclusivity

func WithDeadLetter

func WithDeadLetter(exchange ...string) ConsumerOptions

WithDeadLetter enables dead-lettering for the consumer's queue: rejected (nacked, no requeue), TTL-expired, and over-length messages are routed to a dead letter exchange.

With no argument it uses the managed per-service dead letter topology — a fanout exchange (<service>.fanout.exchange.deadletter) and a bound quorum queue — which the library declares automatically.

Pass a single exchange name to route to an existing external exchange instead; that exchange (and any bindings) must already exist.

func WithDeadLetterRoutingKey

func WithDeadLetterRoutingKey(key string) ConsumerOptions

WithDeadLetterRoutingKey sets a custom routing key for dead-lettered messages. If not set, the original routing key is preserved.

type Header struct {
	Key   string
	Value any
}

Header represents a key-value pair attached to an AMQP message. Value types are constrained by amqp.Table; see the AMQP 0-9-1 spec for allowed types.

type MetricsOption

type MetricsOption func(*metricsConfig)

MetricsOption configures Prometheus metric behavior.

func WithRoutingKeyMapper

func WithRoutingKeyMapper(fn func(string) string) MetricsOption

WithRoutingKeyMapper sets a function applied to every routing key before it is used as a Prometheus label value. Use this to normalize or redact dynamic segments (e.g. UUIDs) from routing keys to prevent unbounded label cardinality. The default is the identity function (labels pass through unchanged). The mapper must return a non-empty string; empty returns are replaced with "unknown".

type OutboxRawPublisher

type OutboxRawPublisher struct {
	// contains filtered or unexported fields
}

OutboxRawPublisher wraps an AMQP Publisher to satisfy the outbox.RawPublisher interface. Headers are received as ce-* prefixed keys and normalized to the AMQP cloudEvents:* wire format before publishing.

func NewOutboxRawPublisher

func NewOutboxRawPublisher(publisher *Publisher) *OutboxRawPublisher

NewOutboxRawPublisher creates an adapter that wraps publisher for use with the outbox relay. The publisher must already be wired to a connection.

func (*OutboxRawPublisher) PublishRaw

func (a *OutboxRawPublisher) PublishRaw(ctx context.Context, routingKey string, payload []byte, headers map[string]string) error

PublishRaw publishes a pre-serialized message to AMQP with the given headers. ce-* headers are normalized to cloudEvents:* per the AMQP binding spec.

type Publisher

type Publisher struct {
	// contains filtered or unexported fields
}

Publisher is used to send messages. It is safe for concurrent use from multiple goroutines.

func NewPublisher

func NewPublisher(opts ...PublisherOption) *Publisher

NewPublisher creates an uninitialized Publisher. Pass it to a publisher Setup function (e.g. EventStreamPublisher, ServicePublisher) which wires it to the connection's channel and exchange. After Start completes, call Publish to send messages.

func (*Publisher) Publish

func (p *Publisher) Publish(ctx context.Context, routingKey string, msg any, headers ...Header) error

Publish sends msg as a JSON-encoded AMQP message with the given routing key. Additional headers can be provided to attach metadata to the message. By default, Publish waits for broker confirmation and returns an error if the broker nacks. Use WithoutPublisherConfirms to disable this behavior.

type PublisherOption

type PublisherOption func(*Publisher)

PublisherOption is a functional option for NewPublisher.

func WithConfirm

func WithConfirm(ch chan amqp.Confirmation) PublisherOption

WithConfirm enables publisher confirms on this publisher's own AMQP channel. Confirmations are delivered to the provided channel. Note that the caller then owns the channel's lifetime. The transport closes any channel registered for notifications when the AMQP channel closes, so with WithReconnect the supplied channel is closed by the disconnect and is not replaced — a publisher that must survive reconnects should let the library own its confirm channel instead.

func WithoutPublisherConfirms

func WithoutPublisherConfirms() PublisherOption

WithoutPublisherConfirms disables publisher confirms for this publisher. By default, Publish() waits for broker confirmation and returns error on nack. Use this opt-out for high-throughput scenarios where occasional message loss is acceptable.

type ReconnectOption added in v0.0.4

type ReconnectOption func(*reconnectConfig)

ReconnectOption configures WithReconnect.

func ReconnectInterval added in v0.0.4

func ReconnectInterval(d time.Duration) ReconnectOption

ReconnectInterval sets the delay before the first retry. Each subsequent attempt doubles it, up to ReconnectMaxInterval.

func ReconnectMaxElapsed added in v0.0.4

func ReconnectMaxElapsed(d time.Duration) ReconnectOption

ReconnectMaxElapsed bounds how long reconnection is attempted before giving up. Zero means never give up.

Giving up is not a silent state: the error is delivered to the CloseListener channel exactly as an unrecovered disconnect is today, so a caller that exits on that signal still exits — just later than it would have without this option.

func ReconnectMaxInterval added in v0.0.4

func ReconnectMaxInterval(d time.Duration) ReconnectOption

ReconnectMaxInterval caps the delay between attempts.

Without a cap, exponential growth quickly reaches delays long enough that a broker which came back minutes ago is still not being retried.

type ServicePublisherOption added in v0.0.3

type ServicePublisherOption func(*servicePublisherConfig)

ServicePublisherOption configures a service request publisher.

func VerifyTarget added in v0.0.3

func VerifyTarget() ServicePublisherOption

VerifyTarget asserts at Start() that the target service's request queue already exists, failing the connection if it does not.

The request queue is declared by the target's own consumer registration, so its absence does not mean "the consumer is busy" -- it means that service has never run against this broker, and every message published to the exchange is discarded.

Off by default: it makes the target's availability a startup dependency of the caller. Use it where a request nobody can execute is a deployment error worth catching at rollout rather than on the first real request.

type ServiceResponsePublisher

type ServiceResponsePublisher[T any] func(ctx context.Context, targetService, routingKey string, event T) error

ServiceResponsePublisher is the callback signature used to publish a response back to the originating service in the request-response pattern.

type Setup

type Setup func(conn *Connection) error

Setup is a setup function that takes a Connection and use it to set up AMQP An example is to create exchanges and queues

func CloseListener

func CloseListener(e chan error) Setup

CloseListener receives close errors from both AMQP channels and the underlying connection. Use this to detect unexpected disconnects and implement fail-fast behavior (e.g. os.Exit).

func EventStreamConsumer

func EventStreamConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup

EventStreamConsumer sets up a durable, persistent event stream consumer on the default "events" topic exchange. For a transient queue, use TransientEventStreamConsumer instead.

func EventStreamPublisher

func EventStreamPublisher(publisher *Publisher) Setup

EventStreamPublisher sets up an event stream publisher

func QueuePublisher

func QueuePublisher(publisher *Publisher, destinationQueueName string) Setup

QueuePublisher sets up a publisher that will send events to a specific queue instead of using the exchange, so called Sender-Selected distribution https://www.rabbitmq.com/sender-selected.html#:~:text=The%20RabbitMQ%20broker%20treats%20the,key%20if%20they%20are%20present.

func RequestResponseHandler

func RequestResponseHandler[T any, R any](routingKey string, handler spec.RequestResponseEventHandler[T, R]) Setup

RequestResponseHandler is a convenience func to set up ServiceRequestConsumer and combines it with PublishServiceResponse

func ServicePublisher

func ServicePublisher(targetService string, publisher *Publisher, opts ...ServicePublisherOption) Setup

ServicePublisher sets up a publisher that sends messages to the targetService's request exchange.

func ServiceRequestConsumer

func ServiceRequestConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup

ServiceRequestConsumer sets up a durable, persistent consumer for incoming service requests. It binds to the connection's own service request exchange using direct routing.

func ServiceResponseConsumer

func ServiceResponseConsumer[T any](targetService, routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup

ServiceResponseConsumer sets up a durable, persistent consumer for responses from targetService. It binds to the target service's response exchange using header-based routing.

func StreamConsumer

func StreamConsumer[T any](exchange, routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup

StreamConsumer sets up a durable, persistent event stream consumer on a named topic exchange.

func StreamPublisher

func StreamPublisher(exchange string, publisher *Publisher) Setup

StreamPublisher sets up an event stream publisher

func TransientEventStreamConsumer

func TransientEventStreamConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup

TransientEventStreamConsumer sets up an event stream consumer that will clean up resources when the connection is closed. For a durable queue, use the EventStreamConsumer function instead.

func TransientStreamConsumer

func TransientStreamConsumer[T any](exchange, routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup

TransientStreamConsumer sets up an event stream consumer that will clean up resources when the connection is closed. For a durable queue, use the StreamConsumer function instead.

func WithErrorChannel

func WithErrorChannel(errorCh chan<- spec.ErrorNotification) Setup

WithErrorChannel specifies a go channel to receive messages such as event failed

func WithLegacySupport

func WithLegacySupport() Setup

WithLegacySupport enables automatic metadata enrichment for messages from legacy (pre-CloudEvents) publishers. When enabled, incoming messages that lack CloudEvents headers will have their Metadata populated with synthetic values (generated UUID, current timestamp, routing key as type, exchange as source).

Without this option, legacy messages arrive with zero-valued Metadata, which is the existing default behavior.

func WithLogger

func WithLogger(logger *slog.Logger) Setup

WithLogger configures structured logging for the connection. If not set, slog.Default() is used.

func WithNotificationChannel

func WithNotificationChannel(notificationCh chan<- spec.Notification) Setup

WithNotificationChannel specifies a go channel to receive messages such as connection event published, consumed, etc.

func WithPrefetchLimit

func WithPrefetchLimit(limit int) Setup

WithPrefetchLimit configures the number of messages to prefetch from the server. To get round-robin behavior between queueConsumers consuming from the same queue on different connections, set the prefetch count to 1, and the next available message on the server will be delivered to the next available consumer. If your consumer work time is reasonably consistent and not much greater than two times your network round trip time, you will see significant throughput improvements starting with a prefetch count of 2 or slightly greater, as described by benchmarks on RabbitMQ.

http://www.rabbitmq.com/blog/2012/04/25/rabbitmq-performance-measurements-part-2/

func WithPropagator

func WithPropagator(p propagation.TextMapPropagator) Setup

WithPropagator configures a TextMapPropagator for the connection. If not set, the global propagator (otel.GetTextMapPropagator()) is used.

func WithPublishSpanNameFn

func WithPublishSpanNameFn(f func(exchange, routingKey string) string) Setup

WithPublishSpanNameFn specifies a function that will get called when a new publish span is created. The function receives the exchange name and routing key. By default "publish {routingKey}" is used.

func WithReconnect added in v0.0.4

func WithReconnect(opts ...ReconnectOption) Setup

WithReconnect re-establishes the connection after an unexpected disconnect, rather than reporting it and leaving the connection dead.

Off by default. Without it a disconnect goes straight to the CloseListener channel and the connection stays down, so a caller that exits on that signal fails fast — the behaviour every existing caller already has.

With it, the same signal is delayed rather than removed. The library redials with exponential backoff, and re-runs every Setup passed to Start against the new connection, so exchanges, queues, consumers and publishers are restored; a *Publisher held by the caller is rebound in place and keeps working. Only when the retry budget is exhausted does the error reach the CloseListener channel, so "reconnecting forever in silence" is not a state this can reach.

The point is to stop a broker outage taking down work that does not depend on the broker — an HTTP API served from a database, say — while keeping the eventual failure just as visible.

func WithSpanNameFn

func WithSpanNameFn(f func(spec.DeliveryInfo) string) Setup

WithSpanNameFn specifies a function that will get called when a new consumer span is created. By default defaultSpanName will be used.

func WithTracing

func WithTracing(tp trace.TracerProvider) Setup

WithTracing configures a TracerProvider for the connection. If not set, the global TracerProvider (otel.GetTracerProvider()) is used.

type TypeMapper

type TypeMapper func(routingKey string) (reflect.Type, bool)

TypeMapper resolves a routing key to a concrete Go type (as reflect.Type). Return false if no type is registered for the key.

Directories

Path Synopsis
cmd
tck-adapter command
Binary amqp-adapter is the reference AMQP adapter for the TCK subprocess protocol.
Binary amqp-adapter is the reference AMQP adapter for the TCK subprocess protocol.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址