Core dependencies:
<!--introduce rabbitmq Correlation dependency--> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.7.2</version> </dependency>
The first model: direct connection
In the model above, there are the following concepts:
P: The producer is the program that sends the message
C: Consumer: the receiver of the message will always wait for the message to arrive.
Queue: message queue, shown in red. Similar to a mailbox, messages can be cached; The producer delivers the message to it, and the consumer takes the message out of it.
producer:
package com.eddie.helloworld; import com.eddie.utiils.RabbitMQUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; import org.junit.Test; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Provider { //Production message @Test public void testSendMessage() throws IOException, TimeoutException { // //Create connection factory object for connection mq // ConnectionFactory connectionFactory = new ConnectionFactory(); // //Set up connection rabbitmq host // connectionFactory.setHost("192.168.2.2"); // //Set port number // connectionFactory.setPort(5672); // //Set which virtual host to connect to // connectionFactory.setVirtualHost("/ems"); // //Set the user name and password to access the virtual host // connectionFactory.setUsername("ems"); // connectionFactory.setPassword("123"); // // //Get connection object // Connection connection = connectionFactory.newConnection(); //Get the connection object through the tool class Connection connection = RabbitMQUtils.getConnection(); //Get channels in connection Channel channel = connection.createChannel(); //Message queue corresponding to channel binding //Parameter 1: queue name automatically created if the queue does not exist //Parameter 2: used to define whether the queue characteristics should be persisted. true persistent queue false not persistent (the queue is saved after service restart, but messages are not saved) //Parameter 3: exclusive exclusive exclusive queue true exclusive queue false not exclusive //Parameter 4: autodelete: whether to automatically delete the queue after consumption is completed. true: automatically delete false: do not automatically delete //Parameter 5: additional parameters channel.queueDeclare("hello",true,false,true,null); //Release news //Parameter 1: switch name parameter 2: queue name parameter 3: additional settings for message delivery (the following parameters ensure that the message still exists and can be consumed after service restart) parameter 4: specific content of the message channel.basicPublish("","hello", MessageProperties.PERSISTENT_TEXT_PLAIN,"hello rabbitmq".getBytes()); // channel.close(); // connection.close(); //Call tool class RabbitMQUtils.closeConnectionAndChanel(channel,connection); } }
consumer:
package com.eddie.helloworld; import com.eddie.utiils.RabbitMQUtils; import com.rabbitmq.client.*; import org.junit.Test; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer { //Production message public static void main(String[] args) throws IOException, TimeoutException { // //Create connection factory object for connection mq // ConnectionFactory connectionFactory = new ConnectionFactory(); // //Set up connection rabbitmq host // connectionFactory.setHost("192.168.2.2"); // //Set port number // connectionFactory.setPort(5672); // //Set which virtual host to connect to // connectionFactory.setVirtualHost("/ems"); // //Set the user name and password to access the virtual host // connectionFactory.setUsername("ems"); // connectionFactory.setPassword("123"); // // //Get connection object // Connection connection = connectionFactory.newConnection(); // //Get the connection object through the tool class Connection connection = RabbitMQUtils.getConnection(); //Get channels in connection Channel channel = connection.createChannel(); //Message queue corresponding to channel binding //Parameter 1: queue name automatically created if the queue does not exist //Parameter 2: used to define whether the queue characteristics should be persisted. true persistent queue false not persistent //Parameter 3: exclusive exclusive exclusive queue true exclusive queue false not exclusive //Parameter 4: autodelete: whether to automatically delete the queue after consumption is completed. true: automatically delete false: do not automatically delete //Parameter 5: additional parameters channel.queueDeclare("hello",true,false,true,null); channel.basicConsume("hello", true, new DefaultConsumer(channel){ //The last parameter: the message retrieved from the message queue public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("new String(body): " + new String(body)); } }); // channel.close(); // connection.close(); } }
Encapsulated public classes:
package com.eddie.utiils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class RabbitMQUtils { private static ConnectionFactory connectionFactory; //private static Properties properties; static{ //The heavyweight resource class is loaded and executed once //Create connection factory object for connection mq connectionFactory = new ConnectionFactory(); //Set up connection rabbitmq host connectionFactory.setHost("192.168.2.2"); //Set port number connectionFactory.setPort(5672); //Set which virtual host to connect to connectionFactory.setVirtualHost("/ems"); //Set the user name and password to access the virtual host connectionFactory.setUsername("ems"); connectionFactory.setPassword("123"); } //Defines the method that provides the connection object public static Connection getConnection() { try { return connectionFactory.newConnection(); } catch (Exception e) { e.printStackTrace(); } return null; } //Method of closing channel and closing connection tool public static void closeConnectionAndChanel(Channel channel, Connection conn) { try { if(channel!=null) channel.close(); if(conn!=null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
The second model (work queue)
Work queues, also known as Task queues, is a task model.
When message processing is time-consuming, the speed of message production may increase
Much faster than the consumption of news. In the long run, news will accumulate
More and more, can not be handled in time. At this point, you can use the work model:
Let multiple consumers bind to a queue and consume messages in the queue together.
Once the messages in the queue are consumed, they will disappear, so the task will not be repeated.
Role:
P: Producer: publisher of the task
C1: consumer - 1, get the task and complete it. It is assumed that the completion speed is slow
C2: consumer-2: get the task and complete the task. It is assumed that the completion speed is fast
Summary: by default, RabbitMQ sends each message to the next consumer in order. On average, each consumer receives the same number of messages. This way of distributing messages is called a loop.
If the producer sends 10 messages, each consumer will get 5 pieces of data. If one consumer goes down when reading the third one, the remaining messages will be lost. In this way, we need to turn off rabbitmq automatic confirmation mechanism and manually give a confirmation mark, which can not only solve the problem of downtime message loss, but also produce the effect of those who can do more
producer:
package com.eddie.workqueues; import com.eddie.utiils.RabbitMQUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.MessageProperties; import org.junit.Test; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Provider2 { //Production message @Test public void testSendMessage() throws IOException, TimeoutException { //Get the connection object through the tool class Connection connection = RabbitMQUtils.getConnection(); //Get channels in connection Channel channel = connection.createChannel(); //Message queue corresponding to channel binding //Parameter 1: queue name automatically created if the queue does not exist //Parameter 2: used to define whether the queue characteristics should be persisted. true persistent queue false not persistent (the queue is saved after service restart, but messages are not saved) //Parameter 3: exclusive exclusive exclusive queue true exclusive queue false not exclusive //Parameter 4: autodelete: whether to automatically delete the queue after consumption is completed. true: automatically delete false: do not automatically delete //Parameter 5: additional parameters channel.queueDeclare("hello",true,false,true,null); //Release news //Parameter 1: switch name parameter 2: queue name parameter 3: additional settings for message delivery (the following parameters ensure that the message still exists and can be consumed after service restart) parameter 4: specific content of the message for(int i = 0; i<20; i++){ channel.basicPublish("","hello", MessageProperties.PERSISTENT_TEXT_PLAIN,(i+"hello rabbitmq").getBytes()); } //Call tool class RabbitMQUtils.closeConnectionAndChanel(channel,connection); } }
Consumer 1:
package com.eddie.workqueues; import com.eddie.utiils.RabbitMQUtils; import com.rabbitmq.client.*; import java.io.IOException; public class Consumer1 { public static void main(String[] args) throws IOException { //Get the connection object through the tool class Connection connection = RabbitMQUtils.getConnection(); //Get channels in connection Channel channel = connection.createChannel(); channel.basicQos(1); //Only one message can be consumed at a time channel.queueDeclare("hello",true,false,true,null); //Parameter 1: queue name parameter 2: message confirmation true consumers automatically confirm consumption to rabbitmq false consumers will not automatically confirm channel.basicConsume("hello", false, new DefaultConsumer(channel){ //The last parameter: the message retrieved from the message queue public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("111new String(body): " + new String(body)); channel.basicAck(envelope.getDeliveryTag(),false); } }); } }
Consumer 2:
package com.eddie.workqueues; import com.eddie.utiils.RabbitMQUtils; import com.rabbitmq.client.*; import java.io.IOException; import static java.lang.Thread.sleep; public class Consumer2 { public static void main(String[] args) throws IOException { //Get the connection object through the tool class Connection connection = RabbitMQUtils.getConnection(); //Get channels in connection Channel channel = connection.createChannel(); channel.basicQos(1); //Only one message can be consumed at a time channel.queueDeclare("hello",true,false,true,null); //Parameter 1: queue name parameter 2: message confirmation true consumers automatically confirm consumption to rabbitmq false consumers will not automatically confirm channel.basicConsume("hello", false, new DefaultConsumer(channel){ //The last parameter: the message retrieved from the message queue public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("222new String(body): " + new String(body)); //Manual confirmation parameter 1: manual confirmation message identification parameter 2: whether to enable multiple messages for confirmation at the same time channel.basicAck(envelope.getDeliveryTag(),false); } }); } }
Set the channel to consume only one message at a time, turn off automatic confirmation of messages, and turn on manual confirmation of messages