rabbitmq

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

rabbitmq

Run Testing GoDoc Trivy Security Scan

RabbitMQ as backend for Queue Package. See the Go RabbitMQ Client Library maintained by the RabbitMQ core team. It was originally developed by Sean Treadway.

Exchanges and Exchange Types

See the Exchanges and Exchange Types section of AMQP 0-9-1 Model Explained.

Direct Exchange

direct-exchange

See the consumer code:

package main

import (
  "context"
  "encoding/json"
  "flag"
  "fmt"
  "log"
  "time"

  "github.com/golang-queue/queue"
  "github.com/golang-queue/queue/core"
  rabbitmq "github.com/golang-queue/rabbitmq"
)

type job struct {
  Message string
}

func (j *job) Bytes() []byte {
  b, err := json.Marshal(j)
  if err != nil {
    panic(err)
  }
  return b
}

var (
  uri          = flag.String("uri", "amqp://guest:guest@localhost:5672/", "AMQP URI")
  exchange     = flag.String("exchange", "test-exchange", "Durable, non-auto-deleted AMQP exchange name")
  exchangeType = flag.String("exchange-type", "direct", "Exchange type - direct|fanout|topic|x-custom")
  q            = flag.String("queue", "test-queue", "Ephemeral AMQP queue name")
  bindingKey   = flag.String("key", "test-key", "AMQP binding key")
)

func init() {
  flag.Parse()
}

func main() {
  taskN := 100
  rets := make(chan string, taskN)

  // define the worker
  w := rabbitmq.NewWorker(
    rabbitmq.WithAddr(*uri),
    rabbitmq.WithQueue(*q),
    rabbitmq.WithExchangeName(*exchange),
    rabbitmq.WithRoutingKey(*bindingKey),
    rabbitmq.WithRunFunc(func(ctx context.Context, m core.TaskMessage) error {
      var v *job
      if err := json.Unmarshal(m.Payload(), &v); err != nil {
        return err
      }
      rets <- v.Message
      return nil
    }),
  )

  // define the queue
  q, err := queue.NewQueue(
    queue.WithWorkerCount(5),
    queue.WithWorker(w),
  )
  if err != nil {
    log.Fatal(err)
  }

  // start the five worker
  q.Start()

  // assign tasks in queue
  for i := 0; i < taskN; i++ {
    go func(i int) {
      if err := q.Queue(&job{
        Message: fmt.Sprintf("handle the job: %d", i+1),
      }); err != nil {
        log.Fatal(err)
      }
    }(i)
  }

  // wait until all tasks done
  for i := 0; i < taskN; i++ {
    fmt.Println("message:", <-rets)
    time.Sleep(50 * time.Millisecond)
  }

  // shutdown the service and notify all the worker
  q.Release()
}

Documentation

Overview

Example (Direct_exchange)

Example_direct_exchange demonstrates how to use RabbitMQ with a direct exchange. This example creates two workers (w1, w2) that both listen to the same queue and exchange, and a producer that sends multiple messages to the queue. The workers process the messages in a round-robin fashion.

Steps: 1. Create a mock message to be sent. 2. Initialize worker w1 with a direct exchange and queue, and define its processing function. 3. Start a queue (q1) with worker w1. 4. Initialize worker w2 with the same direct exchange and queue, and define its processing function. 5. Start a queue (q2) with worker w2. 6. Create a producer worker (w) with the same exchange and routing key. 7. Start a queue (q) with the producer worker. 8. Send the mock message to the queue multiple times. 9. Wait for processing, then release all queues.

Expected Output: - The two workers alternately print the received message.

Unordered Output: worker01 get data: foo worker02 get data: foo worker01 get data: foo worker02 get data: foo

m := mockMessage{
	Message: testMessage,
}
w1 := NewWorker(
	WithQueue("direct_queue"),
	WithExchangeName("direct_exchange"),
	WithExchangeType("direct"),
	WithRoutingKey("direct_exchange"),
	WithRunFunc(func(ctx context.Context, m core.TaskMessage) error {
		fmt.Println("worker01 get data:", string(m.Payload()))
		time.Sleep(100 * time.Millisecond)
		return nil
	}),
)

q1, err := queue.NewQueue(
	queue.WithWorker(w1),
)
if err != nil {
	w1.opts.logger.Fatal(err)
}
q1.Start()

w2 := NewWorker(
	WithQueue("direct_queue"),
	WithExchangeName("direct_exchange"),
	WithExchangeType("direct"),
	WithRoutingKey("direct_exchange"),
	WithRunFunc(func(ctx context.Context, m core.TaskMessage) error {
		fmt.Println("worker02 get data:", string(m.Payload()))
		time.Sleep(100 * time.Millisecond)
		return nil
	}),
)

q2, err := queue.NewQueue(
	queue.WithWorker(w2),
)
if err != nil {
	w2.opts.logger.Fatal(err)
}
q2.Start()

w := NewWorker(
	WithExchangeName("direct_exchange"),
	WithExchangeType("direct"),
	WithRoutingKey("direct_exchange"),
)

q, err := queue.NewQueue(
	queue.WithWorker(w),
)
if err != nil {
	w.opts.logger.Fatal(err)
}

time.Sleep(200 * time.Millisecond)
if err := q.Queue(m); err != nil {
	w.opts.logger.Fatal(err)
}
if err := q.Queue(m); err != nil {
	w.opts.logger.Fatal(err)
}
if err := q.Queue(m); err != nil {
	w.opts.logger.Fatal(err)
}
if err := q.Queue(m); err != nil {
	w.opts.logger.Fatal(err)
}
time.Sleep(200 * time.Millisecond)
q.Release()
q1.Release()
q2.Release()
Output:
worker01 get data: foo
worker02 get data: foo
worker01 get data: foo
worker02 get data: foo
Example (Fanout_exchange)

Example_fanout_exchange demonstrates how to use RabbitMQ with a fanout exchange. This example creates two workers (w1, w2) each listening to a different queue bound to the same fanout exchange, and a producer that sends a message to the exchange. Both workers receive and process the same message.

Steps: 1. Create a mock message to be sent. 2. Initialize worker w1 with a unique queue and the fanout exchange, and define its processing function. 3. Start a queue (q1) with worker w1. 4. Initialize worker w2 with a different queue and the same fanout exchange, and define its processing function. 5. Start a queue (q2) with worker w2. 6. Create a producer worker (w) with the same fanout exchange. 7. Start a queue (q) with the producer worker. 8. Send the mock message to the exchange. 9. Wait for processing, then release all queues.

Expected Output: - Both workers print the received message.

Unordered Output: worker01 get data: foo worker02 get data: foo

m := mockMessage{
	Message: testMessage,
}
w1 := NewWorker(
	WithQueue("fanout_queue_1"),
	WithExchangeName("fanout_exchange"),
	WithExchangeType("fanout"),
	WithRunFunc(func(ctx context.Context, m core.TaskMessage) error {
		fmt.Println("worker01 get data:", string(m.Payload()))
		return nil
	}),
)

q1, err := queue.NewQueue(
	queue.WithWorker(w1),
)
if err != nil {
	w1.opts.logger.Fatal(err)
}
q1.Start()

w2 := NewWorker(
	WithQueue("fanout_queue_2"),
	WithExchangeName("fanout_exchange"),
	WithExchangeType("fanout"),
	WithRunFunc(func(ctx context.Context, m core.TaskMessage) error {
		fmt.Println("worker02 get data:", string(m.Payload()))
		return nil
	}),
)

q2, err := queue.NewQueue(
	queue.WithWorker(w2),
)
if err != nil {
	w2.opts.logger.Fatal(err)
}
q2.Start()

w := NewWorker(
	WithExchangeName("fanout_exchange"),
	WithExchangeType("fanout"),
)

q, err := queue.NewQueue(
	queue.WithWorker(w),
)
if err != nil {
	w.opts.logger.Fatal(err)
}

time.Sleep(200 * time.Millisecond)
if err := q.Queue(m); err != nil {
	w.opts.logger.Fatal(err)
}
time.Sleep(200 * time.Millisecond)
q.Release()
q1.Release()
q2.Release()
Output:
worker01 get data: foo
worker02 get data: foo

Index

Examples

Constants

View Source
const (
	ExchangeDirect  = "direct"
	ExchangeFanout  = "fanout"
	ExchangeTopic   = "topic"
	ExchangeHeaders = "headers"
)

Predefined RabbitMQ exchange types for use in configuration. - ExchangeDirect: Direct exchange type. - ExchangeFanout: Fanout exchange type. - ExchangeTopic: Topic exchange type. - ExchangeHeaders: Headers exchange type.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*options)

Option is a functional option type for configuring the options struct. It allows for flexible and composable configuration of RabbitMQ workers and queues.

func WithAddr

func WithAddr(addr string) Option

WithAddr sets the AMQP server URI.

Parameters: - addr: The AMQP URI to connect to.

Returns: - Option: Functional option to set the address.

func WithAutoAck

func WithAutoAck(val bool) Option

WithAutoAck enables or disables automatic message acknowledgment.

Parameters: - val: true to enable auto-ack, false to disable.

Returns: - Option: Functional option to set autoAck.

func WithExchangeName

func WithExchangeName(val string) Option

WithExchangeName sets the name of the AMQP exchange.

Parameters: - val: The exchange name.

Returns: - Option: Functional option to set the exchange name.

Exchanges are AMQP 0-9-1 entities where messages are sent to. Exchanges take a message and route it into zero or more queues.

func WithExchangeType

func WithExchangeType(val string) Option

WithExchangeType sets the type of the AMQP exchange.

Parameters: - val: The exchange type (direct, fanout, topic, headers).

Returns: - Option: Functional option to set the exchange type.

The routing algorithm used depends on the exchange type and rules called bindings. AMQP 0-9-1 brokers provide four exchange types: - Direct exchange (Empty string) and amq.direct - Fanout exchange amq.fanout - Topic exchange amq.topic - Headers exchange amq.match (and amq.headers in RabbitMQ)

func WithLogger

func WithLogger(l queue.Logger) Option

WithLogger sets a custom logger for the worker or queue.

Parameters: - l: The logger instance.

Returns: - Option: Functional option to set the logger.

func WithQueue

func WithQueue(val string) Option

WithQueue sets the name of the queue to use.

Parameters: - val: The queue name.

Returns: - Option: Functional option to set the queue name.

func WithRoutingKey

func WithRoutingKey(val string) Option

WithRoutingKey sets the AMQP routing key.

Parameters: - val: The routing key.

Returns: - Option: Functional option to set the routing key.

func WithRunFunc

func WithRunFunc(fn func(context.Context, core.TaskMessage) error) Option

WithRunFunc sets the function to execute for each task.

Parameters: - fn: The function to run for each task message.

Returns: - Option: Functional option to set the run function.

func WithTag

func WithTag(val string) Option

WithTag sets the consumer tag for the worker.

Parameters: - val: The consumer tag.

Returns: - Option: Functional option to set the tag.

type ReconnectConfig added in v0.2.0

type ReconnectConfig struct {
	MaxRetries   int
	InitialDelay time.Duration
	MaxDelay     time.Duration
}

ReconnectConfig defines the retry policy for RabbitMQ connection.

type Worker

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

Worker struct implements the core.Worker interface for RabbitMQ. It manages the AMQP connection, channel, and task consumption. Fields: - conn: AMQP connection to RabbitMQ server. - channel: AMQP channel for communication. - stop: Channel to signal worker shutdown. - stopFlag: Atomic flag to indicate if the worker is stopped. - stopOnce: Ensures shutdown logic runs only once. - startOnce: Ensures consumer initialization runs only once. - opts: Configuration options for the worker. - tasks: Channel for receiving AMQP deliveries (tasks).

func NewWorker

func NewWorker(opts ...Option) *Worker

NewWorker creates and initializes a new Worker instance with the provided options. It establishes a connection to RabbitMQ, sets up the channel, and declares the exchange. If any step fails, it logs a fatal error and terminates the process.

Parameters: - opts: Variadic list of Option functions to configure the worker.

Returns: - Pointer to the initialized Worker.

func (*Worker) Queue

func (w *Worker) Queue(job core.TaskMessage) error

Queue publishes a new task message to the RabbitMQ exchange. If the worker is stopped, it returns queue.ErrQueueShutdown.

Parameters: - job: The task message to be published.

Returns: - error: Any error encountered during publishing, or nil on success.

func (*Worker) Request

func (w *Worker) Request() (core.TaskMessage, error)

Request retrieves a new task message from the queue. It starts the consumer if not already started, waits for a message, and unmarshals it into a job.Message. If no message is received within a timeout, it returns queue.ErrNoTaskInQueue.

Returns: - core.TaskMessage: The received task message, or nil if none. - error: Any error encountered, or queue.ErrNoTaskInQueue if no task is available.

func (*Worker) Run

func (w *Worker) Run(ctx context.Context, task core.TaskMessage) error

Run executes the worker's task processing function. It delegates the actual task handling to the configured runFunc.

Parameters: - ctx: Context for cancellation and timeout. - task: The task message to process.

Returns: - error: Any error returned by the runFunc.

func (*Worker) Shutdown

func (w *Worker) Shutdown() (err error)

Shutdown gracefully stops the worker. It ensures shutdown logic runs only once, cancels the consumer, and closes the AMQP connection. If the worker is already stopped, it returns queue.ErrQueueShutdown.

Returns: - error: Any error encountered during shutdown, or nil on success.

Jump to

Keyboard shortcuts

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