This is the 20th day of my participation in the Genwen Challenge
Accumulate over a long period, constant dripping wears away a stone 😄
preface
The previous article explained the concept of RabbitMQ and the basic use of RabbitMQ. This article introduces some common methods of RabbitMQ.
switches
exchangeDeclare
Declaring a switch, exchangeDeclare has multiple overloaded methods, but these overloaded methods are ultimately implemented by the following method. Located in the com. The rabbitmq. Client Channel
public Exchange.DeclareOk exchangeDeclare(String exchange, String type,
boolean durable, boolean autoDelete, boolean internal,
Map<String, Object> arguments);
Copy the code
The return value of this method is exchange. DeclareOk, which indicates that a switch was successfully declared.
Each parameter is described as follows:
-
Exchange: indicates the name of a switch.
-
Type: indicates the switch type. Common ones are fanout, direct, topic
-
Durable: Whether to be durable. Durable True: Durable. Otherwise, it is non-persistent. Persistence saves the switch to disk without losing information when the server restarts. The default is false.
-
AutoDelete: Indicates whether to automatically delete the vm. If autoDelete is set to true, automatic deletion is performed. Automatic deletion is required after at least one queue or switch is bound to the switch. All queues or exchanges bound to this exchange are automatically deleted when they are unbound. The default is false.
-
Internal: Whether the setting is built-in. If set to true, it is a built-in switch and the client cannot send messages directly to the switch, but must route messages to the switch through the switch. The default is false.
-
Arguments: Other structured parameters, such as X-message-TTL, X-dead-letter-exchange, x-dead-letter-routing-key, etc
Example:
public static void main(String[] args) throws IOException {
Connection conn = RabbitMQUtil.createConn();
Channel channel = conn.createChannel();
String exchangName = "test1-gongjie";
HashMap<String, Object> map = new HashMap<>();
// How long messages sent to queues can survive before being discarded (milliseconds)
map.put("x-message-ttl".10000);
channel.exchangeDeclare(exchangName,
BuiltinExchangeType.TOPIC,true.false,map);
RabbitMQUtil.closeConn(channel,conn);
}
Copy the code
exchangeDeclarePassive
Used to check whether the corresponding switch exists. Return normal if it exists; If not, a 404 channel exception is thrown and the channel is closed.
Exchange.DeclareOk exchangeDeclarePassive(String name);
Copy the code
- Name: indicates the switch name
Example:
public static void main(String[] args) throws IOException {
Connection conn = RabbitMQUtil.createConn();
Channel channel = conn.createChannel();
String exchangName = "test1-gongjie1";
AMQP.Exchange.DeclareOk declareOk = channel.exchangeDeclarePassive(exchangName);
}
Copy the code
exchangeDelete
Deleting a Switch
Exchange.DeleteOk exchangeDelete(String exchange);
Exchange.DeleteOk exchangeDelete(String exchange ,
boolean ifUnused);
Copy the code
Exchange indicates the name of a switch and ifUnused indicates whether a switch is deleted when it is not in use. If ifUnused is set to true, the switch is deleted only if it is not in use. If set to false, the switch should be deleted in any case. No error is reported even if the switch does not exist.
Example:
public static void main(String[] args) throws IOException {
Connection conn = RabbitMQUtil.createConn();
Channel channel = conn.createChannel();
String exchangName = "test1-gongjie";
AMQP.Exchange.DeleteOk deleteOk = channel.exchangeDelete(exchangName, false);
System.out.println(deleteOk.protocolClassId() + "= = = ="+ deleteOk.protocolMethodName()); } the result:40====exchange.delete-ok
Copy the code
The queue
queueDeclare
Statement of the queue
public Queue.DeclareOk queueDeclare(a);
public Queue.DeclareOk queueDeclare(String queue,
boolean durable, boolean exclusive, boolean autoDelete,
Map<String, Object> arguments);
Copy the code
QueueDeclare with no arguments creates a rabbitMQ-named queueDeclare by default (amq.gen -s9h… , also known as anonymous queues), an exclusive, automatically deleted, nonpersistent queue. Parameter Description:
-
Queue: indicates the name of a queue.
-
Durable: Whether to be durable. True sets the queue to persistent. Persistent queues are saved to ensure that information is not lost when the server restarts.
-
“Exclusive” : Sets whether to be exclusive. True sets the queue to exclusive. If a queue is declared as an exclusive queue, it is visible only to the connection for which it was first declared and is automatically deleted when the connection is disconnected. There are three points to note here: Exclusive queues are visible based on connections, and different channels of the same Connection are exclusive queues that can access the same Connection at the same time. “First time” means that if a connection has already declared an exclusive queue, other connections are not allowed to create an exclusive queue of the same name. This queue is different from ordinary queues. Even if the queue is persistent, the exclusive queue will be deleted automatically once the connection is closed or the client exits.
-
AutoDelete: Indicates whether to automatically delete the vm. True sets the queue to automatic deletion. Automatic deletion occurs only when at least one consumer is connected to the queue and all consumers connected to the queue are disconnected.
-
Arguments: Set other queue parameters, such as X-message-TTL, X-dead-letter-exchange, x-dead-letter-routing-key, etc.
Example:
public static void main(String[] args) throws IOException {
Connection conn = RabbitMQUtil.createConn();
Channel channel = conn.createChannel();
AMQP.Queue.DeclareOk declareOk = channel.queueDeclare();
System.out.println(declareOk.getQueue() + "= = = ="+ declareOk.protocolMethodName()); } Result: amq.gen -lCUNxThQtii99kmladk -yw====queue.declare-okCopy the code
queueDeclarePassive
Used to check whether the corresponding queue exists. If it does, a 404 channel exception is thrown and the channel is closed.
public Queue.DeclareOk queueDeclarePassive(String queue);
Copy the code
queueDelete
Queue.DeleteOk queueDelete(String queue); Queue.DeleteOkqueueDelete(String queue , boolean ifUnused,
boolean ifEmpty) ;
Copy the code
If ifUnused is set to true, a queue can be deleted only if it is not in use. If ifEmpty is set to true, a queue can be deleted only if it is empty (no messages are piled up in the queue).
queuePurge
Clears messages for a given queue.
Queue.PurgeOk queuePurge(String queue);
Copy the code
Binding and unbinding
queueBind
Bind queues to switches
public Queue.BindOk queueBind(String queue, String exchange, String routingKey);
public Queue.BindOk queueBind(String queue, String exchange, String routingKey, Map
arguments)
,>;
Copy the code
Description of parameters.
- Queue: indicates the queue name.
- Exchange: indicates the name of a switch.
- RoutingKey: a routingKey used to bind a queue to a switch.
- Arguments: Defines some parameters for the binding.
Example:
public static void main(String[] args) throws IOException {
Connection conn = RabbitMQUtil.createConn();
Channel channel = conn.createChannel();
HashMap<String, Object> map = new HashMap<>();
map.put("x-queue-mode".true);
AMQP.Queue.BindOk bindOk = channel.queueBind("queue-gongjie-1"."test1-gongjie"."info");
}
Copy the code
queueUnbind
Unbind queues and switches.
Queue.UnbindOk queueUnbind(String queue, String exchange, String routingKey) throws IOException;
Queue.UnbindOk queueUnbind(String queue, String exchange, String routingKey, Map<String, Object> arguments) throws IOException;
Copy the code
For details about the parameters, see queueBind.
exchangeBind
Binds a switch to a switch
Exchange.BindOk exchangeBind(String destination, String source, String routingKey);
Exchange.BindOk exchangeBind(String destination, String source, String routingKey, Map
arguments)
,>;
Copy the code
- Destination: indicates the destination switch name
- Source: indicates the source switch name
- RoutingKey: indicates the route key
- Arguments: Additional arguments
Example:
public static void main(String[] args) throws IOException {
Connection conn = RabbitMQUtil.createConn();
Channel channel = conn.createChannel();
// Declare source switch
channel.exchangeDeclare ("source"."direct".false , true , null);// Declare the destination switch
channel.exchangeDeclare ("destination"."fanout".false , true , null);
// The switch is bound to the switch
channel.exchangeBind ("destination" , "source"."exKey");
// Declare a queue
channel.queueDeclare ("queue".false.false , true , null);
// Bind the queue to the switch
channel.queueBind ("queue"."destination"."");
// Publish the message
channel.basicPublish ("source"."exKey".null."I am the message sent.".getBytes () ) ;
}
Copy the code
The producer sends a message to the switch source, which finds another switch destination that matches it based on the routing key and forwards the message to destination, where it is stored in the Destination-bound queue.
exchangeUnbind
Unbind a switch from a switch
Exchange.UnbindOk exchangeUnbind(String destination, String source, String routingKey);
Exchange.UnbindOk exchangeUnbind(String destination, String source, String routingKey, Map<String, Object> arguments);
Copy the code
Refer to exchangeBind for an explanation of the parameters.
Send a message
basicPublish
void basicPublish(String exchange, String routingKey,
BasicProperties props, byte[] body);
void basicPublish(String exchange, String routingKey,
boolean mandatory, BasicProperties props, byte[] body);
void basicPublish(String exchange, String routingKey,
boolean mandatory, boolean immediate, BasicProperties props, byte[] body);
Copy the code
Parameter Description:
-
Exchange: The name of the switch to which the message should be sent, if set to an empty string the message will be sent to RabbitMQ’s default switch.
-
RoutingKey: a routingKey by which the switch stores messages to the appropriate queue
-
Props: The basic property set of the message, which contains 14 property members
public static class BasicProperties extends com.rabbitmq.client.impl.AMQBasicProperties {
private String contentType; // Message types such as (text/plain)
private String contentEncoding; // Character encoding
private Map<String,Object> headers; // Request header information
private Integer deliveryMode; // Message delivery mode
private Integer priority; / / priority
private String correlationId; // Used to associate RPC requests and responses.
private String replyTo; // This is used to name a callback queue.
private String expiration; // Expiration time
private String messageId;// Message tokens are used to identify messages
private Date timestamp; // The timestamp of the message sent
private String type; // Message type
private String userId; // User name to connect to MQ
private String appId; // The application representation of the message, such as your computer name
private String clusterId;
Copy the code
-
Byte [] body: payload. The message that needs to be sent
-
Mandatory: When the mandatory parameter is set to true and the switch cannot find a queue based on its type and routing key, RabbitMQ calls basic. Return to Return the message to the producer. When the mandatory parameter is set to false, the message is discarded.
-
Immediate: When the immediate parameter is set to true, if the switch finds no consumers on the queue when routing the message to the queue, the message will not be queued. When none of the queues matching the routing key has a consumer, the message is returned to the producer via basic. Return.
In general, the mandatory parameter tells the server to route the message to at least one queue or return the message to the producer. The immediate parameter tells the server to deliver the message immediately if there are consumers in the queue associated with the message. If there are no consumers on any of the matching queues, the message is returned directly to the producer instead of being queued for the consumer. The immediate parameter is removed from RabbitMQ 3.0. The RabbitMQ official explanation is that the immediate parameter affects the performance of the mirroring queue and increases the complexity of the code. You are advised to use TTL and DLX instead.
Example:
- 1. Set the delivery mode to 2, that is, messages will be persisted (stored on disk) in the server. The message’s priority is set to 1, contentType
For text/plain, userId is the name of the current login user.
channel.basicPublish("exchangeName" , "routingKey".new AMQP.BasicProperties.Builder()
.contentType ("text/plain")
.deliveryMode(2)
.priority(1)
.userId("test")
.build(),
"Send message".getBytes());
Copy the code
- Send a headers message
Map<String, Object> headers = new HashMap<String, Object>() ;
headers.put("token"."782");
channel.basicPublish("exchangeName"."routingKey".new AMQP.BasicProperties.Builder()
.headers(headers)
.build(),
"Send message".getBytes()) ;
Copy the code
- Send a message with expiration time
channel.basicPublish("exchangeName"."routingKey".new AMQP.BasicProperties.Builder()
. expiration ("6000")
.build(),
"Send message".getBytes());
Copy the code
News consumption
RabbitMQ can consume messages in two modes: Push and Pull. In push mode, basic. Consume is used, while in pull mode, basic. Get is called.
Push mode
There are too many basicConsume methods in the Channel class, so here are a few commonly used ones
String basicConsume(String queue , Consumer callback);
String basicConsume(String queue , boolean autoAck, Consumer callback);
String basicConsume(String queue , boolean autoAck , Map<String , Object>
arguments, Consumer callback);
String basicConsume(String queue , boolean autoAck , String consumerTag,
Consumer callback);
String basicConsume(String queue , boolean autoAck , String consumerTag,
boolean noLocal , boolean exclusive , Map<Str ng Object> arguments,
Consumer callback);
Copy the code
Parameter description:
- Queue: indicates the name of a queue
- AutoAck: Sets whether to automatically acknowledge the message. If autoAck is set to false, then channel.basicAck needs to be called to confirm that the message has been received successfully.
- ConsumerTag: A consumer label used to distinguish multiple consumers.
- NoLocal: If set to true, messages sent by producers in the same Connection cannot be sent to consumers in that Connection.
- “Exclusive” : Sets whether to be exclusive
- Arguments: Sets additional parameters for the consumer
- Callback: Sets the consumer’s callback function. Used to handle messages pushed by RabbitMQ. DefaultConsumer, for example, requires the client to rewrite its methods.
channel.basicConsume("work".false.new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("Consumer News: + new String(body));
/** * Parameter 1: confirm that the message in the queue is consumed * Parameter 2: enable multiple messages simultaneously true Enable */
// Confirm the message manually
channel.basicAck(envelope.getDeliveryTag(),false); }});Copy the code
Pull mode
The channel.basicGet method fetches messages individually, and the return value is GetResponse. The basicGet method of the Channel class has no other overloaded methods.
GetResponse basicGet(String queue, boolean autoAck);
Copy the code
Where queue stands for the name of the queue, if autoAck is set to false, then channel.basicack is displayed to confirm that the message was received successfully.
Confirmation and rejection at the consumer end
basicReject
void basicReject(long deliveryTag, boolean requeue);
Copy the code
- DeliveryTag: The number of the message
- Requeue: if this parameter is set to true
RabbitMQ
The message is saved again
Queues so that they can be sent to the next subscriber consumer; If the Requeue parameter is set to false, RabbitMQ will immediately remove messages from the queue.
The basic. Reject command can only Reject one message at a time. If you want to Reject messages in batches, you can use the basic. Nack command.
basicNack
void basicNack(long deliveryTag, boolean multiple, boolean requeue);
Copy the code
- DeliveryTag: The number of the message
- Multiple: When set to false, the reject number is
deliveryTag
At this timebasicNack
Methods andbasicReject
If the multiple parameter is set to true, less than is rejecteddeliveryTag
Number all messages that have not been confirmed by the current consumer. - Requeue: if this parameter is set to true
RabbitMQ
The message is saved again
Queues so that they can be sent to the next subscriber consumer; If the Requeue parameter is set to false, RabbitMQ will immediately remove messages from the queue.
basicRecover
Whether to restore the message to the queue.
Basic.RecoverOk basicRecover(a) throws IOException;
Basic.RecoverOk basicRecover(boolean requeue) throws IOException;
Copy the code
This channel.basicRecover method is used to request RabbitMQ to resend unacknowledged messages. With the Requeue parameter set to true, unacknowledged messages will be re-queued and sent to as many consumers as possible. Instead of spending again. If the Requeue parameter is set to false, the message will be redelivered to itself. By default, this parameter is true if requeue is not set.
basicAck
void basicAck(long deliveryTag, boolean multiple) throws IOException;
Copy the code
- DeliveryTag: The number of the message
- Multiple: When set to false, the confirmation consumption number is
deliveryTag
If this parameter is true, the consumption is less than or equal todeliveryTag
Value for all messages.
References:
1, Teacher Zhu Zhonghua RabbitMQ combat Guide book
2, the RabbitMQ BasicProperties
- If you have any questions or errors in this article, please feel free to comment. If you find this article helpful, please like it and follow it.