rabbitmq queue delay is implemented in two ways

Transfer:  https://blog.csdn.net/u014308482/article/details/53036770

 

ps: article inside Latency Queuing delay queue =

What is the delay queue
objects stored in the queue delay is certainly delay corresponding to the message, the so-called "delayed message" refers to the future when the message is sent, the consumer does not want to get the message immediately, but after waiting for a specified time, consumers only to get the news to consume.

Scene One: In order system, there are usually 30 minutes to make payments after the next single user, if there is no successful payment within 30 minutes, then the order will be a process. This is the delay queue can be used to send order information to the delay queue.

Scene Two: the user wants to work at a specified time by cell phone remote control home smart devices. This time may be sent to the user instruction queue delays, set time when the instruction to the instruction and then pushed to the intelligent device.

How to implement RabbitMQ queue later
method
AMQP and RabbitMQ queue protocol itself does not directly support the queuing delay, but the delay can be simulated by the following characteristic features queue.
However, we can RabbitMQ curve achieved by the two delay queue characteristics:

Characteristic. 1, the To Live Time (the TTL)
RabbitMQ may be provided for Queue Message for the x-expires or provided x-message-ttl, to control the lifetime of the message, if the timeout (in both the first set time expires, whichever ), the message becomes a dead letter (badmail)

RabbitMQ for queue message expiration time may be provided in two ways.

A: By setting queue attributes, all the messages in the queue have the same expiration time.
B: the message is provided separately, may be different for each message TTL.
If at the same time, the expiration time of the message, whichever smaller between the TTL value. Message time to live TTL value exceeds the setting of the queue once, become dead letter

Characteristic 2, Dead Letter Exchanges (DLX)
RabbitMQ Queue may be configured in x-dead-letter-exchange and x-dead-letter-routing- key ( optional) two parameters, if there is the dead letter queue, according to which two parameters reroute forward to a specified queue.

x-dead-letter-exchange: After emergence dead letter the dead letter back to the designated exchange
the dead letter back the specified routing-key transmission appears after dead letter: x-dead-letter -routing-key
queues appear dead letter of case are:

Message queue or the TTL expired
queue maximum length
message is rejected (basic.reject or basic.nack) and the consumer side requeue = false
then The above two properties, the TTL set rules when the message becomes a dead letter queue using the characteristic that it can be re-DLX? forwarded to another Exchange or Routing Key, this time the message will be re-consumed.

Setting method:
Step 1: Set TTL produce dead letter, there are two ways Per-Message TTL and Queue TTL, the first may be an expiration time for use in most scenes for each message set, the second set for the queue? expiration time for delay-time job scene

There are other ways, such as dead letter generate consumer consumption basic.reject refuse or basic.nack (consumer premise to set the property requeue = false)

Per-Message TTL (time to expiration of a set each message) (official documentation)
Java Client resides only transmits a message to the queue of 60 seconds:

byte [] = messageBodyBytes "the Hello, World!" the getBytes ();.
AMQP.BasicProperties = new new AMQP.BasicProperties Properties ();
properties.setExpiration ( "60000"); // set the message expiration time is 60 seconds
channel.basicPublish ( "my-exchange", " routing-key", properties, messageBodyBytes);
then transmitted to the corresponding queue // this message, if the consumer is not within 60 seconds, it becomes dead letter


Queue TTL (an expiration time of the entire queue settings)
to create a queue, the queue message expiration time is 30 minutes (30 minutes in this queue? Consumer spending did not delete messages, delete messages in the queue to become dead letter)

java client mode:

Map<String, Object> args = new HashMap<String, Object>();
args.put("x-expires", 1800000);
channel.queueDeclare("myqueue", false, false, false, args);

rabbitmqctl command mode (. * for all the queues, the queue may be replaced specified):
. "*" rabbitmqctl set_policy expiry '{ "Expires": 1800000}' --apply-to Queues

rabbitmqctl (the Windows):
. "*" rabbitmqctl set_policy expiry "{" "Expires" ": 1800000}" Queues to --apply-

Step: forwarding rules setting a dead message (if no rule directly discarding badmail )

Dead Letter Exchanges setting method (official documents)
the Java Client mode:
// Declare a direct exchange mode
channel.exchangeDeclare ( "some.exchange.name", "Direct");
// declare a queue, the queue when there myqueue when dead letter generation, will be forwarded to the switch some.exchange.name
the Map <String, Object> = new new args the HashMap <String, Object> ();
args.put ( "X-Dead-Letter-Exchange", "some. exchange.name ");

//? If the dead letter will be forwarded to key routes some-routing-key to some.exchange.name, if not set the default routing key used when sending messages to this queue is
//args.put("x-dead- Key-routing-Letter "," Key-some-routing ");
channel.queueDeclare (" MyQueue ", to false, to false, to false, args);














Plug-Source Address:
https://github.com/rabbitmq/rabbitmq-delayed-message-exchange

Download plugin:
https://bintray.com/rabbitmq/community-plugins/rabbitmq_delayed_message_exchange

Installation:
into the plug-in installation directory
{rabbitmq-server} / plugins / ( you can check out the current existing plug-in)
to download the plug
rabbitmq_delayed_message_exchange

https://bintray.com/rabbitmq/community-plugins/download_file?file_path=rabbitmq_delayed_message_exchange-0.0.1.ez wget
1
(if irregularities on the downloaded file name manually rename it as:
rabbitmq_delayed_message_exchange-0.0.1.ez)

启用插件
rabbitmq-plugins enable rabbitmq_delayed_message_exchange

(Plug closed)
rabbitmq-plugins disable rabbitmq_delayed_message_exchange
. 1
2
. 3
. 4
Plugins
used delayed-messaging by declaring a characteristic x-delayed-message type Exchange
x-delayed-message is of the type provided by the plug itself is not rabbitmq

Elided code ... ... //
the Map <String, Object> = new new args the HashMap <String, Object> ();
args.put ( "X-DELAYED-type", "Direct");
channel.exchangeDeclare ( " Exchange-My "," X-DELAYED-message ", to true, to false, args);
// ... ... More code
. 1
2
. 3
. 4
. 5
, when sending a message by adding the header" x-delay "parameter a control delay time of the message

// ... elided code ...
byte[] messageBodyBytes = "delayed payload".getBytes("UTF-8");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("x-delay", 5000);
AMQP.BasicProperties.Builder props = new AMQP.BasicProperties.Builder().headers(headers);
channel.basicPublish("my-exchange", "", props.build(), messageBodyBytes);
// ... more code ...

使用示例:
消息发送端:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Send {
// 队列名称
private final static String EXCHANGE_NAME="delay_exchange";
private final static String ROUTING_KEY="key_delay";

@SuppressWarnings("deprecation")
public static void main(String[] argv) throws Exception {
/**
* 创建连接连接到MabbitMQ
*/
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.12.190");
factory.setUsername("admin");
factory.setPassword("admin");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

// 声明x-delayed-type类型的exchange
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-delayed-type", "direct");
channel.exchangeDeclare(EXCHANGE_NAME, "x-delayed-message", true,
false, args);


Map <String, Object> = new new headers the HashMap <String, Object> ();
// 2016 provided / 11 / 04,16: 45: push section 12 a message to the consumer side of
a Date now = new new a Date ();
a Date timeToPublish = new Date ( "2016/11 / 04,16: 45: 12");

String readyToPushContent = "publish at " + sf.format(now)
+ " \t deliver at " + sf.format(timeToPublish);

headers.put("x-delay", timeToPublish.getTime() - now.getTime());

AMQP.BasicProperties.Builder props = new AMQP.BasicProperties.Builder()
.headers(headers);
channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, props.build(),
readyToPushContent.getBytes());

// close the channel and connected
channel.close ();
Connection.close ();
}
}

message the receiving end:

import java.text.SimpleDateFormat;
import java.util.Date;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class Recv {

// 队列名称
private final static String QUEUE_NAME = "delay_queue";
private final static String EXCHANGE_NAME="delay_exchange";

public static void main(String[] argv) throws Exception,
java.lang.InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.12.190");
factory.setUsername("admin");
factory.setPassword("admin");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

channel.queueDeclare(QUEUE_NAME, true,false,false,null);
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
channel.basicConsume(QUEUE_NAME, true, queueingConsumer);
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
System.out.println("****************WAIT***************");
while(true){
QueueingConsumer.Delivery delivery = queueingConsumer
.nextDelivery(); //

String message = (new String(delivery.getBody()));
System.out.println("message:"+message);
System.out.println("now:\t"+sf.format(new Date()));
}

} catch (Exception exception) {
exception.printStackTrace();

}

}
}

Starts receiving end, the transmitting end starts
operating results:

WAIT *************** ****************
the Message: publish AT 2016-11-04 16: 44: 16.887 The deliver 2016-AT 16 11-04: 45: 12.000
now: 2016-11-0416: 45: 12.023

results are shown in our 2016-11-0416: 45: 12.023 of the message received from the time we set 2016-11-0416 : 45: 12.023 23 millisecond delay

Note: When using transmission rabbitmq-delayed-message-exchange widget message to the queue number may not be visible in the web management interface, it does not affect the normal function using

Note: Use process found that when an enabled RAM node rabbitmq-delayed-message-exchange plug-ins will not start at the time of restart, view the log found a Timeout exception developer explained that this is a node in the boot process will synchronize the cluster related data caused by startup timeout, and is not recommended Ram node

Guess you like

Origin www.cnblogs.com/duoduo264/p/11453708.html