Generic RabbitMQ Worker for Rust
Important: This library relies on the rabbitmq-delayed-message-exchange plugin for its delayed retry functionality. Please ensure it is enabled on your RabbitMQ broker.
A flexible, generic RabbitMQ worker library for Rust, inspired by the ease of use of MassTransit in .NET. It provides the core building blocks for creating robust message consumers with built-in support for automatic retries (immediate and delayed) and a dead-letter queue (DLQ).
Philosophy
This library provides a GenericRabbitMQWorker that handles a single, resilient connection. It is designed to be run inside a loop that your application controls. This gives you full authority over the lifecycle, including:
- Graceful Shutdown: You decide how to listen for shutdown signals (like
Ctrl+C) and stop the worker. - Reconnect Strategy: You control the delay and logic for reconnecting after a failure.
Features
- Generic Worker: Implement the
MessageHandlertrait for any message type. - Convention over Configuration: Sensible defaults for queue, exchange, and routing key names.
- Automatic Retries: Built-in support for MassTransit-style delayed redelivery.
- Dead-Letter Queue (DLQ): Failed messages are automatically sent to a DLQ after all retry attempts are exhausted.
- Configurable QoS: Set the prefetch count to control message throughput.
- Delayed Message Support: Uses the
rabbitmq-delayed-message-exchangeplugin for efficient delayed messaging. - Async First: Built on top of
lapinandtokio.
Prerequisites
This library requires the rabbitmq-delayed-message-exchange plugin to be enabled on your RabbitMQ broker. You can enable it with the following command:
Usage
-
Add the dependency to your
Cargo.toml:[] = { = "<your-git-repo-url>" } # Or from crates.io when published = { = "1.0", = ["derive"] } = { = "1", = ["full"] } = "0.4" = "0.9" -
Define your message struct:
use Deserialize; -
Implement the
MessageHandlertrait:use async_trait; use ; use Arc; ; -
Build the run loop in your
main.rs:The application is responsible for managing the worker's lifecycle. This allows for flexible shutdown and reconnect strategies.
use ; use Arc; use Duration; async
How It Works
- Worker: The
GenericRabbitMQWorkeris a lightweight struct that holds the configuration and message handler. Itsrun()method attempts to connect and process messages in a single, long-lived session. - Run Loop: The application creates a
loopthat continuously callsworker.run(). Thetokio::select!macro allows the application to simultaneously wait for the worker to finish (or fail) and listen for external shutdown signals (likeCtrl+C). - Auto-Reconnect: If
worker.run()returns anErr(e.g., the connection is lost), the application logs the error, waits for a configurable period, and theloopattempts to callrun()again. - Graceful Shutdown: If the shutdown signal is received, the
loopis broken, and the application can terminate cleanly.
License
This project is licensed under the Apache-2.0 License.