Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use RabbitMQ

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to use RabbitMQ for you. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Practical application skills of RabbitMQ 1.1. Preface

Due to project reasons, we will deal more with RabbitMQ later, so let's sort out the practical skills of RabbitMQ application to avoid mining pit in the future.

1.2. Overview

RabbitMQ has several important concepts: virtual hosts, switches, queues, and bindings

Virtual host: a virtual host holds a set of switches, queues and bindings. We can control permissions from the granularity of the virtual host level.

Switch: Exchange is used to forward messages, it does not store messages, and if there is no Queue queue bound to Exchange, it will directly discard the data sent by the producer.

The switch also has an important concept associated with it: the routing key. Which queue the message is forwarded to depends on the routing key.

Binding: it binds switches and queues, which is a many-to-many relationship, that is, multiple switches can be bound to the same queue, or multiple queues can be bound to one switch.

1.3. Exchanger

There are four types of switch modes: Direct, topic, Headers and Fanout.

1.3.1. Direct Exchage

Direct mode uses the default switch of RabbitMQ, and it is also the simplest mode, which is suitable for relatively simple scenarios.

As shown in the figure below, using Direct mode, we need to create different queues, while the default switch uses the value of the Routing key routing key to decide which queue to forward to. As you can see, multiple queues can be specified for routing key binding.

1.3.2. Topic Exchange

The Topic pattern is mainly matched according to wildcards, which is similar to fuzzy matching. When the matching pattern matches the routing key, the switch can forward the message to the specified queue.

The route key is a string separated by a period (.), such as a.b.c

(*) represents a word in a specified position, (#) represents zero or more words, such as a.room.b.words, indicates a random word between an and b, and b can be followed by n words, such as a.x.b.c.d.e

The difference between Topic mode and Direct mode is that the switch needs to be specified by itself, and the route key supports fuzzy matching, for example:

RabbitTemplate.convertAndSend ("topicExchange", "a.x.b.d", "hello world!"); 1.3.3 Headers Exchage

Headers also matches according to rules, but it does not match according to routing keys. Headers has a custom matching rule, which sets the matching key value on the headers attribute of the message. When one or all of these key-value pairs match, the message will be delivered to the corresponding queue. This mode is relatively inefficient and is generally not recommended.

1.3.4. Fanout Exchange

Fanout is the famous broadcast mode. It does not need a routing key and will send messages to all queues bound to it. Even if the routing key is configured, it will be ignored.

1.4. Complicated situation

First of all, our Direct mode, in the case of one producer and one consumer, corresponds to a sender and a queue A to receive. There is no doubt about what to send and receive.

When a single producer sends a message in Direct mode, and multiple consumers, that is, multiple identical queue are enabled, the message is evenly shared among multiple consumers without repeated consumption (provided that the ack is normal)

When a switch binds two queues in Topic mode, the routing keys overlap. The following code specifies the routing key topic.message to send messages, and both queues queueMessage and queueMessages can receive the same message. That is to say, topic mode can achieve a form similar to broadcast mode, or even more flexible. Whether it can be forwarded to a message is determined by the routing key.

Compared with Fanout mode, if we want to send packets to consumer queues, we need to specify different routing keys, while Fanout mode needs to specify different switches and queue bindings, which is actually used in combination with the actual situation.

@ Configurationpublic class TopicRabbitConfig {final static String message = "topic.message"; final static String messages = "topic.messages"; @ Bean public Queue queueMessage () {return new Queue (TopicRabbitConfig.message);} @ Bean public Queue queueMessages () {return new Queue (TopicRabbitConfig.messages);} @ Bean TopicExchange exchange () {return new TopicExchange ("exchange") } @ Bean Binding bindingExchangeMessage (Queue queueMessage, TopicExchange exchange) {return BindingBuilder.bind (queueMessage) .to (exchange) .with ("topic.message");} @ Bean Binding bindingExchangeMessages (Queue queueMessages, TopicExchange exchange) {return BindingBuilder.bind (queueMessages) .to (exchange) .with ("topic.#");}} 1.5. Springboot configuration

Our common configurations are as follows

Spring.rabbitmq.addresses=localhost:5672spring.rabbitmq.username=userspring.rabbitmq.password=123456spring.rabbitmq.virtual-host=/spring.rabbitmq.connection-timeout=1000## sets snooping limit: up to 10, default 5spring.rabbitmq.listener.simple.concurrency=5spring.rabbitmq.listener.simple.max-concurrency=10spring.rabbitmq.publisher-confirms=truespring.rabbitmq.publisher-returns=truespring.rabbitmq.template.mandatory=truespring.rabbitmq.listener.simple.acknowledge-mode=manual

The last four configurations need to be explained:

Spring.rabbitmq.publisher-confirms is true, which means that after the producer message is sent, the broker of the MQ receives the message, and sends a receipt to confirm the receipt. If not set, the message may be lost.

Spring.rabbitmq.publisher-returns is true, which means that when the message cannot reach the Broker side of the MQ, the listener will be used for subsequent processing of the unreachable message. This usually occurs only if the routing key is not configured properly, or when the MQ is down.

Spring.rabbitmq.template.mandatory when the above two are true, this must be matched with true, otherwise the above two will not work

Spring.rabbitmq.listener.simple.acknowledge-mode means manual confirmation for manual. The actual production should be set to manual to ensure that your business is processed. Pay attention to the idempotent nature of the business and can be called repeatedly. The manual confirmation code is as follows

@ Componentpublic class RabbitReceiver {@ RabbitListener (bindings = @ QueueBinding (value = @ Queue (value = "queue-1", durable= "true"), exchange = @ Exchange (value = "exchange-1", durable= "true", type= "topic") IgnoreDeclarationExceptions = "true"), key = "springboot.*") @ RabbitHandler public void onMessage (Message message Channel channel) throws Exception {System.err.println ("- -") System.err.println ("consumer Payload:" + message.getPayload ()); Long deliveryTag = (Long) message.getHeaders (). Get (AmqpHeaders.DELIVERY_TAG); / / manual ACK to get deliveryTag channel.basicAck (deliveryTag, false);}} 1.6. Queue Properti

Queue: name of the queue

Durable: indicates that the data in the queue is persisted to disk for true, which can prevent data loss from mq downtime and restart.

Exclusive: indicates exclusiveness for true. Only one current connection is allowed to access the queue. No new connection is allowed to enter the queue if the connection is currently connected, otherwise an error is reported. When the connection is disconnected, the current queue will be destroyed.

AutoDelete: indicates automatic deletion for true. When no Connection is connected to the queue, it will be deleted automatically.

Arguments: this parameter is used to add some extra parameters, as shown in the following picture

For example, adding a x-message-ttl of 5000 means that the message will expire if it is not processed for more than 5 seconds.

X-expires setting 120000 indicates that the queue is deleted if it is not consumed within 2 minutes.

XMMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXMAXUTHYTHYTHYTHY bytes represents the maximum length and number of bytes of the transmitted data

The data will be forwarded to the dead letter queue and stored in the queue attribute that needs to be expired or failed to be processed. These data will be forwarded to the dead letter queue for storage, create a normal switch and queue binding, enter the switch name to the value of x-dead-letter-exchange, and enter the routing key to match the routing key of the dead letter queue.

X-max-priority, which indicates that priority is set, with a range of 0,255. This priority is meaningful only when messages are piled up. The higher the number, the higher the priority.

When x-queue-mode is lazy, it means lazy queue, which was introduced after 3.6.0. Compared with the default mode, lazy queue mode stores messages generated by producers directly to disk, which certainly increases IO overhead, but it is suitable for situations where a large number of messages are piled up. Because when a large number of messages are piled up and there is not enough memory, the messages will be transferred to disk, which is also time-consuming and cannot receive new messages during the process. If you need to convert a normal queue to a lazy queue, you need to delete the original queue and recreate a lazy queue binding.

1.7. Switch Properti

Exchange: switch name

Type: switch typ

Durable: persistence, same queue

AutoDelete: whether to delete automatically, same queue

Internal: if true, this exchange cannot be used by client to push messages, but only for binding between exchange and exchange.

Arguments: additional parameter. At present, there is only an alternate-exchange, which means that when the producer sends a message to this switch and cannot route the queue of the switch, it will try to route to the switch specified by this parameter. If the routing key matches, it will be routed to the queue specified by alternate-exchange, which is equivalent to forwarding. It just matches the previous parameter internal. If you do not want this switch to act as a routing queue, you can set internal to true. All messages are forwarded to a switch designated by alternate-exchange, which routes the specified queues

As shown in the following figure: exchange0 sets the alternate-exchange switch to exchange1, and the producer sends data to exchange0 with the routing key test1. If the route is not reached in exchange0, it is forwarded to exchange1 to determine that the route matches, and then sent to queue queue1.

1.8. Disk and memory

In the RabbitMQ management interface, when we deploy the cluster, we can see that the Info field in the Nodes node may be * * disc or ram**, indicates disk storage or memory storage. In fact, when deploying a cluster, we need at least one disk storage, which means that the metadata such as switches, queues, bindings, users, etc., can be persisted to disk, and the RabbitMQ can be restored to the original state after one restart. When there is only one node, it must be disk storage. Memory storage also has its advantages, that is, it is more efficient and faster.

1.9. Report an error case

When the following error is reported, you must have an exclusive queue, that is, a queue with the exclusive attribute set. Because different channels created by the same connection can access the same queue, this exclusive attribute will result in a resource locking error, that is, the following error.

So we know that if you set the queue to the exclusive property, don't create a new connection to access the same queue.

This is the end of ESOURCE_LOCKED-cannot obtain exclusive access to locked queue xxxxxx's article on "how to use RabbitMQ". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report