Documentation
¶
Overview ¶
Package rabbitmq provides a thin, testable wrapper around RabbitMQ producers and consumers.
Design constraints (for use in application frameworks):
- No viper, no global singletons, no log.Fatal inside the library.
- Producer and Consumer interfaces are mock-friendly.
- Start consumers from a dedicated cmd process (not inside HTTP servers); see README.
- Call Close on shutdown; use NotifyClose on the connection for reconnect logic in your app.
High availability: multiple broker URLs (failover), startup retry via NewConnWithRetry / NewProducerWithRetry. High concurrency: ConsumeWithConcurrency plus PrefetchCount (Qos) tuning.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidConfig indicates configuration validation failed. ErrInvalidConfig = errors.New("rabbitmq: invalid config") // ErrNotInitialized indicates a producer or consumer was not created. ErrNotInitialized = errors.New("rabbitmq: not initialized") // ErrNoURL indicates no AMQP URL could be built from config. ErrNoURL = errors.New("rabbitmq: no url") )
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// URL is a full amqp:// connection string (highest precedence).
URL string
// URLs is a failover list of amqp:// connection strings.
URLs []string
// Host is the broker hostname when URL is empty.
Host string
// Port is the broker port (default 5672).
Port int
// User is the login name (default guest).
User string
// Password is the login password (default guest).
Password string
// Vhost is the virtual host path.
Vhost string
// Timeout bounds overall connect operations. It is also used as the TCP
// dial and handshake timeout when DialTimeout is zero and AMQPConfig is nil.
Timeout time.Duration
// Heartbeat is the AMQP heartbeat interval when AMQPConfig is nil.
Heartbeat time.Duration
// DialTimeout bounds the TCP dial when AMQPConfig is nil (default: Timeout).
DialTimeout time.Duration
// PrefetchCount is applied via Channel.Qos before consume (default 1).
PrefetchCount int
// PrefetchGlobal sets the global Qos flag when applying PrefetchCount.
PrefetchGlobal bool
// MaxRedelivery is the maximum number of redeliveries allowed for a message
// whose handler keeps failing. Once exceeded the message is rejected with
// requeue=false so the broker can route it to a dead-letter exchange.
// Zero means unlimited redelivery. Exact counting uses the x-delivery-count
// header (quorum queues); on other queues only the redelivered flag is known.
MaxRedelivery int
// Retry optional startup connect retry (dial + channel open only).
Retry RetryConfig
// AMQPConfig optional full override of driver config (TLS, SASL, etc.).
AMQPConfig *amqp.Config
// ErrorHandler optional callback when a message handler returns an error.
ErrorHandler func(error)
}
Config holds RabbitMQ connection settings.
func ConfigDefault ¶
func ConfigDefault() Config
ConfigDefault returns production-oriented defaults (URL/Host must still be set).
func (*Config) Validate ¶
Validate checks the configuration and fills defaults without dialing the broker.
func (Config) ValidateDSN ¶
ValidateDSN ensures at least one dial URL can be built.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn wraps an AMQP connection.
func NewConn ¶
NewConn creates a connection from config (first successful URL when URLs is set). The config is validated before any network I/O; ctx cancels the TCP dial.
func NewConnWithRetry ¶
NewConnWithRetry creates a connection with exponential-backoff startup retry. Retries stop as soon as ctx is cancelled.
func (*Conn) NotifyClose ¶
NotifyClose registers a listener for connection close notifications.
type Consumer ¶
type Consumer interface {
Consume(ctx context.Context, queue string, handler MessageHandler) error
ConsumeWithConcurrency(ctx context.Context, queue string, concurrency int, handler MessageHandler) error
EnsureQueue(name string) error
Close() error
}
Consumer abstracts message consumption for tests and application wiring.
func NewConsumer ¶
NewConsumer creates a consumer (returns mock-friendly Consumer interface). The config is validated before connecting; ctx bounds the connect.
type ConsumerHandle ¶
type ConsumerHandle interface {
// Close stops consumption and releases resources.
Close() error
// NotifyClose returns a channel of connection errors when supported by the underlying consumer.
NotifyClose() <-chan *amqp.Error
}
ConsumerHandle adds lifecycle helpers without changing the Consumer interface.
func WrapConsumer ¶
func WrapConsumer(c Consumer) ConsumerHandle
WrapConsumer returns a ConsumerHandle for graceful shutdown and reconnect hooks.
type MessageHandler ¶
MessageHandler is invoked per delivery; return nil to ack.
type Producer ¶
type Producer interface {
Publish(ctx context.Context, exchange, routingKey string, body []byte, opts ...PublishOption) error
Close() error
}
Producer abstracts message publishing for tests and application wiring.
func NewProducer ¶
NewProducer creates a producer (returns mock-friendly Producer interface). The config is validated before connecting; ctx bounds the connect.
Example ¶
package main
import (
"context"
"fmt"
"github.com/andywang2011/go-rabbitmq"
)
func main() {
cfg := rabbitmq.ConfigDefault()
p, err := rabbitmq.NewProducer(context.Background(), cfg)
if err != nil {
fmt.Println("unavailable")
return
}
defer p.Close()
fmt.Println("ok")
}
Output: unavailable
type PublishOption ¶
type PublishOption func(*amqp.Publishing)
PublishOption configures a published message.
func WithContentType ¶
func WithContentType(ct string) PublishOption
WithContentType sets Content-Type.
type RetryConfig ¶
type RetryConfig struct {
// MaxAttempts is the total number of attempts (including the first).
MaxAttempts int
// InitialDelay is the first backoff pause.
InitialDelay time.Duration
// MaxDelay caps exponential backoff.
MaxDelay time.Duration
// Multiplier scales delay after each failed attempt.
Multiplier float64
}
RetryConfig controls exponential-backoff retry during startup connect only.
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns startup retry defaults.