dawdler-rabbitmq-core
Module introduction
Provides a RabbitMQ connection pool implemented with pool2.
1. Add the dependency to the pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-rabbitmq-core</artifactId>
2. properties file description
host=localhost # IP address of the RabbitMQ server; if an HA cluster is used, just put the VIP address here (required, no default)
port=5672 # port number (default: 5672)
virtualHost=/ # virtual host (default: /)
username=mq_user # username (required, no default)
password=mq_user # password (required, no default)
networkRecoveryInterval=3000 # automatic reconnect interval after a network interruption, 3000 ms, in milliseconds (default: 3000)
automaticRecoveryEnabled=true # enable automatic recovery; after an abnormal disconnection the AMQP client reconnects automatically and restores the channel in place (confirm mode and QoS remain effective after recovery, consumer subscriptions are re-registered automatically, and channels held during the disconnect can be used again once the connection is restored; the reconnect interval is specified by networkRecoveryInterval); when false, dead connections after an abnormal disconnect are immediately invalidated in the pool and the pool supplies new connections (default: true)
shutdownTimeout=30000 # shutdown timeout, 30000 ms, in milliseconds (default: 30000)
pool.maxTotal=32 # maximum number of producer connections (default: 8); consumers' long-lived connections use a separate pool and do not consume this quota
pool.maxWaitMillis=5000 # maximum wait time of the pool (in milliseconds) (default: 30000); when the pool is exhausted this timeout throws an exception instead of blocking the calling thread forever
pool.minIdle=0 # minimum number of idle connections (default: 0)
pool.maxIdle=4 # maximum number of idle connections (default: 8)
consumer.pool.maxTotal=32 # upper bound of the consumer pool (one long-lived connection per bean owning a @RabbitListener) (default: max(pool.maxTotal,32))
confirmSelect=true # all channels borrowed from the pool have confirm mode enabled uniformly, for scenarios where you use ConfirmListener yourself; RabbitProvider.publishIfFailedRetry enables confirm on its own (idempotently) and does not depend on this setting (default: true)
channel.size=16 # number of channels per connection (default: 16)
channel.getTimeout=15000 # timeout for obtaining a channel (in milliseconds) (default: 15000, compatible with the legacy key channel.getTimeOut)
ttlTime=5000 # time before a failed consumer message is retried (in milliseconds); must be used together with @RabbitListener (default: 5000); the retry message re-enters the work queue using the queue name as its routingKey
compensationConfirmTimeoutMillis=5000 # timeout for waiting for broker confirmation of the compensation publish (retry/dead-letter redelivery) after a consumption failure (in milliseconds) (default: 5000); on timeout the result is treated as unknown and the original message is requeued so that the consumer absorbs the duplicate idempotently; the JVM parameter -Ddawdler.rabbitmq.compensationConfirmTimeoutMillis takes precedence over this setting
publishRetryMaxTimes=3 # maximum number of retries for a failed publishIfFailedRetry publish (default: 3); beyond this the message is moved to the failure queue; the JVM parameter -Ddawdler.rabbitmq.publishRetry.maxTimes takes precedence over this setting
publishRetryBaseDelayMillis=1000 # base backoff delay for publish retries (milliseconds); the actual delay is this value * 2^(number of retries already performed), capped at 60000 (default: 1000); the JVM parameter -Ddawdler.rabbitmq.publishRetry.baseDelayMillis takes precedence over this setting
publishRetryConfirmTimeoutMillis=5000 # timeout for synchronously waiting for broker confirmation after publishing (milliseconds) (default: 5000); the JVM parameter -Ddawdler.rabbitmq.publishRetry.confirmTimeoutMillis takes precedence over this setting
The configuration file supports multiple environments, a unified configuration center, encryption, and variable substitution. See Multi-environment configuration.
compensationConfirmTimeoutMillis and publishRetry* are resolved uniformly when the AMQPConnectionFactory constructs an instance of this configuration file (JVM parameter -Ddawdler.rabbitmq.* > configuration file key > default value); the @RabbitListener listeners and RabbitProvider of the same configuration file share the resolved result through factory getters.
3. RabbitInjector annotation
Used to inject a RabbitProvider.
The value of the RabbitInjector annotation takes the fileName, which is the name of the configuration file (without the .properties suffix).
For details, see:
dawdler-server-plug-rabbitmq implements injection on the dawdler-server side.
dawdler-client-plug-rabbitmq implements injection on the web side.
4. RabbitListener annotation
Used to mark a method as listening for messages of a given queue. In the dawdler implementation, multiple methods in one class can be annotated with RabbitListener. Note that one class shares one Connection, so pay attention to setting the number of Channels.
/**
*
* Marks whether a method is a RabbitMQ consumer; the method format is fixed as void methodName(Message message)
* @author jackson.song
* @version V1.0
*/
@Retention(value = RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface RabbitListener {
/**
* Specifies the RabbitMQ configuration file name
*/
String fileName();
/**
* Queue name
*/
String queueName();
/**
* routingKey
*/
String[] routingKey() default {};
/**
* Exchange
*/
String[] exchange() default {};
/**
* Whether to acknowledge automatically
*/
boolean autoAck() default true;
/**
* Whether to retry
*/
boolean retry() default false;
/**
* Send to the dead-letter queue on failure
*/
boolean failedToDLQ() default true;
/**
* Number of retries
*/
int retryCount() default 12;
/**
* Number of consumers for this listener; must not exceed channel.size=16 # number of channels per connection
*/
int concurrentConsumers() default 1;
/**
* prefetchCount limits how many messages the server sends to each consumer at a time.
*/
int prefetchCount() default 1;
}
5. RabbitProvider class
//Push a message to a queue, e.g.: publish("", "routingKey", null, "hello world".getBytes());
public void publish(String exchange, String routingKey, BasicProperties props, byte[] body) throws Exception {
Connection con = null;
Channel channel = null;
try {
con = connectionFactory.getConnection();
channel = con.createChannel();
channel.basicPublish(exchange, routingKey, props, body);
} finally {
if (channel != null) {
channel.close();
}
if (con != null) {
con.close();
}
}
}
//See the source code for the rest
6. Usage outside the dawdler architecture
//By calling the getInstance method of AMQPConnectionFactory
public static AMQPConnectionFactory getInstance(String fileName);
//Obtain the AMQPConnectionFactory by calling this method; fileName does not include the .properties suffix.
//For example: if fileName is myRabbitMQ, you need to create the configuration file myRabbitMQ.properties on the project classpath.
Note: when AMQPConnectionFactory runs on the client or the server side, there is no need to close it manually; dawdler closes the related resources automatically.
When used outside the dawdler architecture, you need to call AMQPConnectionFactory.shutdownAll(); to release the resources.
7. Publish-failure retry system properties
publishIfFailedRetry returns only after synchronously waiting for broker confirmation (confirm ack) after publishing. When it is not confirmed (nack / wait timeout / connection closed while waiting, result unknown), it automatically enters exponential-backoff retries; messages that still exceed the maximum retry count are moved to the failure queue (rabbit_fail_exchange). A failure of the publish itself (exception when obtaining a connection / creating a channel / calling basicPublish) is thrown synchronously to the caller and does not enter the retry chain. Configuration precedence: JVM parameter (-D) > RabbitMQ configuration file (see Section 2) > default value:
| Property name | Default value | Description |
|---|---|---|
dawdler.rabbitmq.publishRetry.maxTimes | 3 | Maximum number of retries for a failed publish; beyond this the message is moved to the failure queue; can also be set in the RabbitMQ configuration file with the key publishRetryMaxTimes, the JVM parameter takes precedence |
dawdler.rabbitmq.publishRetry.baseDelayMillis | 1000 | Base backoff delay for retries (milliseconds); the actual delay is baseDelayMillis * 2^(number of retries already performed), capped at 60000; can also be set in the RabbitMQ configuration file with the key publishRetryBaseDelayMillis, the JVM parameter takes precedence |
dawdler.rabbitmq.publishRetry.confirmTimeoutMillis | 5000 | Timeout for synchronously waiting for broker confirmation after publishing (milliseconds); on timeout the result is treated as unknown and the message enters the retry chain; the retry semantics are at-least-once, so after a timeout the message may actually have already reached the broker and resending causes duplicate delivery, requiring the consumer to be idempotent or deduplicate; can also be set in the RabbitMQ configuration file with the key publishRetryConfirmTimeoutMillis, the JVM parameter takes precedence |
-Ddawdler.rabbitmq.publishRetry.maxTimes=5
-Ddawdler.rabbitmq.publishRetry.baseDelayMillis=2000
-Ddawdler.rabbitmq.publishRetry.confirmTimeoutMillis=10000
8. Consumption-failure compensation publish system properties
When an @RabbitListener method throws an exception (with autoAck=false), the framework redelivers the message to the retry exchange (rabbit_retry_exchange, which dead-letters back to the work queue after ttlTime expires) or to the failure exchange (rabbit_fail_exchange), and synchronously waits for the broker's publisher confirm -- the original message is acknowledged only after the compensation message is confirmed to have landed; on nack / confirmation timeout / publish exception the original message is requeued (basicNack(requeue=true)), guaranteeing no message loss. Confirmation timeout precedence: JVM parameter > configuration file (compensationConfirmTimeoutMillis, see Section 2) > default value 5000:
| Property name | Default value | Description |
|---|---|---|
dawdler.rabbitmq.compensationConfirmTimeoutMillis | 5000 | Timeout for waiting for broker confirmation of the compensation publish (retry/dead-letter redelivery) after a consumption failure (milliseconds); on timeout the result is treated as unknown and the original message is requeued so that the consumer absorbs the duplicate idempotently; can also be set in the RabbitMQ configuration file with the key compensationConfirmTimeoutMillis, the JVM parameter takes precedence |
-Ddawdler.rabbitmq.compensationConfirmTimeoutMillis=10000
9. Idempotency requirements for consumers
The message delivery semantics of this framework are at-least-once, and the following scenarios cause the same message to be consumed more than once, so the consumer (the @RabbitListener method) must be idempotent or deduplicate:
- Compensation publish confirmation timeout: on confirmation timeout the broker may actually have received the compensation message, but the framework treats it as "result unknown" and requeues the original message; if the compensation message landed, the original message is delivered again as well.
- Channel failure during ack/nack: the connection drops before the consumer acks (or nacks/requeues after a compensation failure) once processing is done; that delivery is unacknowledged on the broker side, so the message is redelivered after the connection recovers -- even if the business logic has already succeeded.
- Publish retry chain (
publishIfFailedRetry): the publisher resends after the confirmation wait times out, so the broker may receive the message twice (see Section 7). - Broker-side redelivery: unacknowledged messages when a consumer disconnects (abnormal close), master-slave switchover of mirrored queues, and other internal broker mechanisms also cause redelivery.
Common idempotency techniques: a business unique key plus a database unique constraint, a message-id deduplication table (Redis SET NX / database insert), state-machine checks (skip orders that have already been processed), and so on.