rabbitmq

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 11 Imported by: 0

README

go-rabbitmq

Thin, testable RabbitMQ producer and consumer wrapper.

Install

go get github.com/andywang2011/go-rabbitmq@v0.1.0

Quick start

import (
	"context"
	"fmt"

	"github.com/andywang2011/go-rabbitmq"
)

cfg := rabbitmq.ConfigDefault()

p, err := rabbitmq.NewProducer(context.Background(), cfg)
if err != nil {
	fmt.Println("unavailable")
	return
}
defer p.Close()
fmt.Println("ok")

Examples

export AMQP_URL='amqp://guest:guest@127.0.0.1:5672/'
cd go-rabbitmq/examples/producer && go run .
cd go-rabbitmq/examples/consumer && go run .

License

MIT — see LICENSE.

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

View Source
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) DSN

func (c Config) DSN() string

DSN returns an amqp URL; URL field takes precedence over host parts.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration and fills defaults without dialing the broker.

func (Config) ValidateDSN

func (c Config) ValidateDSN() error

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

func NewConn(ctx context.Context, cfg Config) (*Conn, error)

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

func NewConnWithRetry(ctx context.Context, cfg Config) (*Conn, error)

NewConnWithRetry creates a connection with exponential-backoff startup retry. Retries stop as soon as ctx is cancelled.

func (*Conn) Channel

func (c *Conn) Channel() (*amqp.Channel, error)

Channel opens a new channel; caller must Close it.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection; safe to call multiple times.

func (*Conn) NotifyClose

func (c *Conn) NotifyClose() <-chan *amqp.Error

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

func NewConsumer(ctx context.Context, cfg Config) (Consumer, error)

NewConsumer creates a consumer (returns mock-friendly Consumer interface). The config is validated before connecting; ctx bounds the connect.

func NewConsumerWithRetry

func NewConsumerWithRetry(ctx context.Context, cfg Config) (Consumer, error)

NewConsumerWithRetry creates a consumer with exponential-backoff startup retry. Retries stop as soon as ctx is cancelled.

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

type MessageHandler func(ctx context.Context, msg amqp.Delivery) error

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

func NewProducer(ctx context.Context, cfg Config) (Producer, error)

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

func NewProducerWithRetry

func NewProducerWithRetry(ctx context.Context, cfg Config) (Producer, error)

NewProducerWithRetry creates a producer with exponential-backoff startup retry. Retries stop as soon as ctx is cancelled.

type PublishOption

type PublishOption func(*amqp.Publishing)

PublishOption configures a published message.

func WithContentType

func WithContentType(ct string) PublishOption

WithContentType sets Content-Type.

func WithJSON

func WithJSON() PublishOption

WithJSON sets application/json.

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.

Jump to

Keyboard shortcuts

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