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 ¶
- Constants
- type Option
- func WithAddr(addr string) Option
- func WithAutoAck(val bool) Option
- func WithExchangeName(val string) Option
- func WithExchangeType(val string) Option
- func WithLogger(l queue.Logger) Option
- func WithQueue(val string) Option
- func WithRoutingKey(val string) Option
- func WithRunFunc(fn func(context.Context, core.TaskMessage) error) Option
- func WithTag(val string) Option
- type ReconnectConfig
- type Worker
Examples ¶
Constants ¶
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 ¶
WithAddr sets the AMQP server URI.
Parameters: - addr: The AMQP URI to connect to.
Returns: - Option: Functional option to set the address.
func WithAutoAck ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithRoutingKey sets the AMQP routing key.
Parameters: - val: The routing key.
Returns: - Option: Functional option to set the routing key.
func WithRunFunc ¶
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.
type ReconnectConfig ¶ added in v0.2.0
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 ¶
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 ¶
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 ¶
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.
