Combined with live cases to achieve rabbitmq messaging

ps: This article is longer, readers still need patience to read. A lot of dry goods.

To improve performance, but also to achieve the project specification, we will be in dealing with the introduction of messaging middleware message queues in the distributed project. Middleware is a role for decoupling, there is a performance boost. Messaging middleware are in contact with each of us every day, I believe we have used or heard of the US Mission US Mission. From a programmer's point of view the US Mission takeaway involving three roles. [Business] [rider] [customers]. The relationship between these three simple to understand as follows

Three role structure

The following case will be explained through the code, the following is a project structure
Project structure
rabbit-demo

place an order

Today we highlight the process orders, why not choose an order process to select the other two processes it. Because the process is not delivered the message queue. If you have to plan for the block I can only think the message is a message consumer. And it made the order process and orders are the same. Readers should consider who are the usual meal. We should be more understanding of the order.

Under pay-line

We think about the process before the US Mission to launch our takeaway meal of. Customers are carried out to pay the merchant shop consumption. What are the drawbacks of this model exist. This must be the business of the shop is large enough, more than enough staff to be able to let consumers do not jam up. But this increases the cost of business. Therefore, under the conditions of this limitation of our online transactions it was born.
Offline transactions

Online Trading

With the US group we only need the phone ordering, businesses will choose to accept the line, and then shipped. This is the case of a single process. The rider is behind the business processes.

Our customers are the equivalent of adding a message to the message queue, the message body is our orders. In the US Mission takeaway system may be more than the same time a single point which led to a merchant processing time, however, this is our mq it as a caching mechanism first customer orders localization, mq order of FIFO the message methodical distributed to the hands of the only businesses. This leads many people to solve our problems in a complicated orders.
Well, more than that of the benefits we mq. Here we look at the code in a centralized manner by specific mq to send a message.
Online Trading

FIG mq structure

structure

Preparing the Environment

rabbitmq installation

Since RabbitMQ is written in Erlang, and therefore need to install Erlang.

  • Http://www.erlang.org/downloads installed through the installation files corresponding to obtain
  • Increase environmental variables ERLANG_HOME = D: \ Program Files \ erl9.3 (here is my directory installation directory, you have to replace your own directory)
  • Modify environment variables Path, after the original value plus ";% ERLANG_HOME% \ bin"

After installing Erlang, we can install the RabbitMQ.

  • Http://www.rabbitmq.com/install-windows-manual.html to download the installation package for installation
  • Increase environmental variables RABBITMQ_HOEM = D: \ Program Files \ RabbitMQ Server \ rabbitmq_server-3.7.5 (directory here is my installation directory, you have to replace your own directory)
  • Modify environment variables Path, after the original value plus ";% RABBITMQ_HOME% \ sbin"

After installing, RabbitMQ as a service to be started in accordance with the default

Run the command rabbitmq-plugins enable rabbitmq_management open Web management plug-in
start up
access through a browser http: // localhost: 15672, and log in with the default user guest, password is the guest, after the login page:
Browser Interface

springboot project to build

About springboot build here will not elaborate. We expanded directly in zxhtom framework. Just add the following dependency on the inside on the line


<!-- rabbit mq -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Then we only need to create a RabbitConfigclass. The role of this class is to make mq check and complete the creation of the various components of the project started at the beginning. Since the spring to complete the natural need to add on the class @Configurationnotes.

Only need to complete the above operation, our service mq even done! The remaining production should be consumed.
Pay more attention to here is RabbitConfigthe class that there is something in the end, we look at the code before we start to understand the principles under mq.

rabbitmq component disassembly

Queue: a message queue, in direct contact with the object producers.
Exchange: Switch normal circumstances the consumer is in direct contact with the switch.
Routing Key: two different objects in contact with producers and consumers. This requires routing key to both objects associated
Binding: bound together by routing key.

Here is the relationship between consumers, producers, queues, switches, rk, binding

relationship

Four kinds of switches

Above we understand the internal structure mq, in fact, it is very simple. But sometimes we have mq broadcast mode, and some ad hoc mode. These are the so be it. Yes it is what we in this section - switches.

Direct Exchange

As the name suggests is the direct-connect switch []. Asked to send message key exactly matches a particular route. We have the following code queue and directExchange switch queue1 bound together by the DIRECTION. So we send a message that the message must be marked DIRECTION


@Bean
public Binding binding1(){
    return BindingBuilder.bind(queue1()).to(directExchange()).with(DIRECTIONKEY);
}

public void directionSend() {
    rabbitTemplate.convertAndSend(RabbitConfig.DIRECTEXCHANGE, "directionKey", msg);
}

Fanout Exchange

fanout Chinese translation for the [output], where we understand to be broadcast. [Switch] Radio
broadcast, which means that everyone can receive, here defined as the need to re-queue all times as long as the bindings on the switch can receive. Other key do not want to switch needs to signal to match. Fanout Exchange is our common broadcast mode, as long as the subscription will receive the message. As some real estate agent is this model, as long as you leave a phone number of real-estate dynamics will push on your cell phone.


@Bean
public Binding fanoutBinding1(){
    return BindingBuilder.bind(queue1()).to(fanoutExchange());
}
@Bean
public Binding fanoutBinding2(){
    return BindingBuilder.bind(queue2()).to(fanoutExchange());
}
@Bean
public Binding fanoutBinding3(){
    return BindingBuilder.bind(queue3()).to(fanoutExchange());
}
@Bean
public Binding fanoutBinding4(){
    return BindingBuilder.bind(queue4()).to(fanoutExchange());
}

The following code is the long message is sent to all the queues will receive the message Fanout Exchange

public void fanoutSend1() {
    rabbitTemplate.convertAndSend(RabbitConfig.FANOUTEXCHANGE, RabbitConfig.QUEUETHIRD, msg);
}

Topic Exchange

The routing keys and a pattern matching, as will be understood here in the Direction Exchange key can be matched by some regular
#: represents one or more words,
*: indicates a word
stuff in the zxh #: can be matched zxh; zxh;.. zxh.abc; zxh.ab.sd.sa
stuff in the zxh *: can be matched zxh.test; zxh.demo.

Headers Exchange

Do not handle routing keys. The content of the message but matches the transmitted headers property. Specifies a key-value pair when binding Queue and Exchange; RabbitMQ when the message is sent to the message to be taken when the specified Exchange headers and bind to the matching key; exact match if the message is routed to this queue , it will not be routed to the queue. headers property is a key-value pair may be a Hashtable, key-value pair may be of any type. The fanout, direct, topic of routing keys need to be a string.

X-match rule matching the following two types:

x-match = all: means all the key-value pairs are matched in order to receive messages

x-match = any: that as long as there will be able to receive messages matching the key-value

//请求数据中必须符合headerValues中任意一个参数
@Bean
public Binding headBinding1(){
    Map<String,Object> headerValues = new HashMap<>();
    headerValues.put("type", "cash");
    headerValues.put("aging", "fast");
    return BindingBuilder.bind(queue1()).to(headersExchange()).whereAll(headerValues).match();
}

Dead Letter Queue

Fourth switch described above finished. There is also something called us a dead letter queue
or the US Mission takeaway column, we usually finish a single point after the US group, but uncertainty is not now necessary to make business. This time we will not choose the next single. US group will prompt us to complete the payment within 30 minutes, is responsible for the failure. Consider also the US group could not have been where you are waiting for orders. You will take this memory of the people.


@Bean
public Queue deadLetterQueue(){
    Map<String, Object> arguments = new HashMap<String, Object>();
    //设置此死信队列消息过期后,消息转发到那个队列上
    arguments.put("x-dead-letter-exchange", DIRECTEXCHANGE);
    arguments.put("x-dead-letter-routing-key", DIRECTIONKEY);
    return new Queue(QUEUEDEAD, true, false, false,arguments);
}

@Bean
public Binding deadBinding(){
    return BindingBuilder.bind(deadLetterQueue()).to(directExchange()).with(QUEUEDEAD);
}
public void deadSend() {
    MessagePostProcessor processor = new MessagePostProcessor() {
        @Override
        public Message postProcessMessage(Message message) throws AmqpException {
            message.getMessageProperties().setExpiration("60000");
            return message;
        }
    };
    log.info("延时消息开始发送:");
    rabbitTemplate.convertAndSend(RabbitConfig.DIRECTEXCHANGE, RabbitConfig.QUEUEDEAD, msg,processor);
}

We can achieve by sending a message the code above, the delay effect will appear. This is the effect of the code we usually 30 minutes to pay.

to sum up

This article is longer, readers still need patience to read. A lot of dry goods.

Join team

# Join team

Micro-channel public number

Micro-channel public number

Guess you like

Origin www.cnblogs.com/zhangxinhua/p/11504265.html