In the last article, we successfully built RabbitMQ on the server, which is equivalent to the red box in the middle.
If you want to use RabbitMQ, you must also use two roles - Produces and Consumer, so let's specifically implement RabbitMQ to send and receive messages.
1. Working mode
RabbitMQ provides six working modes for different scenarios, as shown below:
The six modes correspond to: simple mode, work queues, Publish/Subscribe publish and subscribe mode, Routing routing mode, Topics topic mode and RPC remote call mode.
In the figure, P represents the message producer, C represents the message consumer, X represents the switch, and red represents the queue.
2. Simple mode
Simple mode is the simplest mode in rabbit MQ. In this mode, there are only two roles, a message producer and a message consumer.
2.1. Message provider
First, create a java project through Maven, and then complete the construction of the message producer through the following steps:
- Import dependency: import the dependency required by RabbitMQ
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.8.0</version> </dependency>
- Write code: write code in the main function
public static void main(String[] args) throws Exception { //1. Create a connection factory ConnectionFactory factory = new ConnectionFactory(); //2. Set parameters factory.setHost("ip address");//ip default value localhost factory.setPort(5672); //Port default 5672 factory.setVirtualHost("/");//Virtual machine defaults/ factory.setUsername("user name");//User name: default guest factory.setPassword("password");//Password default guest //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); //5. Create a Queue. Because it is a simple mode, you do not need to use a switch channel.queueDeclare("hello",false,false,false,null); //6. Send message String str = "hello world !!! hello rabbitmq !!!"; channel.basicPublish("","hello_world",null,str.getBytes()); }
Because the RabbitMQ message sending port is 5672, we need to add relevant security group rules on the Alibaba cloud console, and then execute the main function. After successful execution, you can check whether the message was sent successfully on the web management page of RabbitMQ:
Such a message provider is created. Let's explain some codes in the main function:
-
ConnectionFactory factory = new ConnectionFactory();, Create a connection factory and set some parameters to specify the address and other information of the RabbitMQ Server.
-
Connection connection = factory.newConnection();, Create a connection to the RabbitMQ Server.
-
Channel channel = connection.createChannel();, Create a pipe.
-
channel.queueDeclare("hello",false,false,false,null);, Created a queue. The queuedeclare method has five parameters. The specific meanings are as follows:
- Queue name
- Whether the queue is persistent, that is, whether to save messages. Messages can be stored in memory and on disk. They are stored in memory by default (the value is false)
- Whether the queue can be consumed by only one consumer. By default, only one consumer is allowed to consume (the value is false)
- Whether the queue will be automatically deleted after the last consumer is disconnected. true means automatic deletion
- Other parameters are null here for quick use.
-
channel.basicPublish("","hello",null,ste.getBytes());, Send a message. The basicpublish method has four parameters. The specific meanings are as follows:
- Switch name, because no switch is used, fill in ""
- Route name,
- Other parameter information
- Send message data
2.2 message consumer
In order to distinguish from message producers, a new project is created through Maven. The steps of building a message consumer are similar to those of a message producer:
- Import dependency: the same as above
- Write code: write code in the main function
public static void main(String[] args) throws Exception{ //1. Create a connection factory ConnectionFactory factory = new ConnectionFactory(); //2. Set parameters factory.setHost("120.26.166.77");//ip default value localhost factory.setPort(5672); //Port default 5672 factory.setVirtualHost("/");//Virtual machine defaults/ factory.setUsername("long");//User name: default guest factory.setPassword("czl212121");//Password default guest //3. Create a Connection Connection connection = factory.newConnection(); //4. Create a Channel Channel channel = connection.createChannel(); //5. To create a Queue, we need to use Exchange (switch) before creating a Queue, but it can be omitted because it is an introductory case. channel.queueDeclare("hello",false,false,false,null); //How to perform interface callback for consumption of pushed messages DeliverCallback deliverCallback=(consumerTag, delivery)->{ System.out.println("consumerTag: "+consumerTag); System.out.println(new String(delivery.getBody())); }; //A callback interface for canceling consumption, such as when the queue is deleted during consumption CancelCallback cancelCallback=(consumerTag)->{ System.out.println("Message consumption interruption"); }; channel.basicConsume("hello",true,deliverCallback,cancelCallback); }
After executing the main function:
On the web management page, the messages in the queue have been finished:
The code in the main function is not different from the code in the message provider. The only difference is that it changes from message sending to message receiving.
channel.basicConsume("hello",true,deliverCallback,cancelCallback); Indicates the acceptance message. The four parameters in basicconsume indicate:
- Queue name
- Whether to answer automatically after consumption is successful. true means to answer automatically. false means to answer manually
- Callback function for consumption success
- Callback function for consumption failure
3. Work queues work queue mode
Work queue is also a mode in RabbitMQ. It is not different from the simple mode. The code is almost the same. The only difference is that there are multiple message consumers in the work queue mode.
In order to obtain specific effects, we simply modify the cases in the simple mode:
- Message producer: change the message sending to input and send on the console. Only some modified codes are posted below
//String str = "hello world !!! hello rabbitmq"; //channel.basicPublish("","hello",null,str.getBytes()); //It is used to replace the above code to complete the message content input by the console Scanner scanner = new Scanner(System.in); while (!scanner.hasNext("#")){ String str = scanner.nextLine(); channel.basicPublish("","hello",null,str.getBytes()); System.out.println("Message sent:"+str); }
- Message consumers: run two message consumers at the same time
When the message producer sends a message, the following effects will be produced:
As can be seen from the above figure, in the work queue mode, the queue distributes messages through rotation training, which is simply understood as rain and dew, one message for each person.