Java operation RabbitMQ add queue, consume queue and three switches

Posted by Fabrizzio PHP on Fri, 06 Dec 2019 12:45:32 +0100

I. send message to queue (producer)

Create a new maven project and add the following dependencies to the pom.xml file

<dependencies>
    <dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <version>3.6.5</version>
    </dependency>
</dependencies><br>

Create a new P1 class

package com.rabbitMQ.test;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author mowen
 * @create 2019/11/20-11:23
 */
public class P1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //Message queue name
        String queueName="queue";
        //Instance connection factory
        ConnectionFactory connectionFactory=new ConnectionFactory();
        //Set address
        connectionFactory.setHost("192.168.128.233");
        //Set port
        connectionFactory.setPort(5672);
        //Set user name
        connectionFactory.setUsername("mowen");
        //Set password
        connectionFactory.setPassword("123456");
        //Get connection (similar to jdbc)
        Connection connection = connectionFactory.newConnection();
        //Create channel
        Channel channel = connection.createChannel();
        //Declare the queue.
        //Parameter 1: queue name
        //Parameter 2: persistence (true means that the queue will still exist when the server is restarted)
        //Parameter 3: exclusive queue (the private queue that can be used by the creator and automatically deleted after disconnection)
        //Parameter 4: automatically delete the queue when all consumer clients are disconnected
        //Parameter 5: other parameters of the queue
        channel.queueDeclare(queueName,true,false,false,null);

        for (int i = 0; i < 10; i++) {
            String msg="msg"+i;
            // Basic release message
            // The first parameter is the switch name
            // The second parameter is the queue mapped route key
            // The third parameter is the other properties of the message
            // The fourth parameter is the body of sending information
            channel.basicPublish("",queueName,null,msg.getBytes());
        }

        channel.close();
        connection.close();
    }
}

After running, the browser will enter the RabbitMQ console and switch to the queue to see

2. Get queue message (consumer)

Create a new C1 class

package com.rabbitMQ.test;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author mowen
 * @create 2019/11/20-13:12
 */
public class C1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //Message queue name
        String queueName="queue";
        //Instance connection factory
        ConnectionFactory connectionFactory=new ConnectionFactory();
        //Set address
        connectionFactory.setHost("192.168.128.233");
        //Set port
        connectionFactory.setPort(5672);
        //Set user name
        connectionFactory.setUsername("mowen");
        //Set password
        connectionFactory.setPassword("123456");
        //Get connection (similar to jdbc)
        Connection connection = connectionFactory.newConnection();
        //Create channel
        Channel channel = connection.createChannel();

        // Create a consumer
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // The callback called when the consumer receives the message
                System.out.println("C3 Receive:" + new String(body));
            }
        };

        //Bind consumption to specified queue
        //The first is the queue name
        //The second is whether to confirm automatically
        //The third is consumers
        channel.basicConsume(queueName,true,consumer);

    }
}

Output after operation is

Generally, the consumer will not shut down and will wait for the queue message all the time. You can close the program manually.

channel.basicConsume(queueName,true,consumer); the true value in channel.basicconsume is to automatically confirm after receiving the message, and the false value is to cancel the automatic confirmation.

At the end of the handleDelivery method

channel.basicAck(envelope.getDeliveryTag(),false);

To receive a manual confirmation message. Consumers can have multiple and consume a queue at the same time;

When there are multiple consumers consuming the same queue at the same time, the received messages are evenly distributed (the consumers have confirmed the messages received by each consumer before receiving),

But when one of the consumers has poor performance, it will affect other consumers, because it has to wait for it to finish receiving messages, which will drag other consumers down.

Basic QoS method of channel can be set

//Set the maximum number of accepted messages
// After setting this parameter, make sure to turn it off automatically
channel.basicQos(1);

III. fanout switch

Fan switch is the basic switch type. It will send the received messages to the bound queue in the form of broadcast. Because it does not need to be filtered by conditions, it is the fastest.

Create a fanout class in the producer project

package com.rabbitMQ.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author mowen
 * @date  2019/11/20-11:23
 */
public class fanout {
    public static void main(String[] args) throws IOException, TimeoutException {
        //Switch name
        String exchangeName="fanout";
        //Switch name type
        String exchangeType="fanout";
        //Message queue name
        String queueName1="fanout.queue1";
        String queueName2="fanout.queue2";
        String queueName3="fanout.queue3";
        //Instance connection factory
        ConnectionFactory connectionFactory=new ConnectionFactory();
        //Set address
        connectionFactory.setHost("192.168.128.233");
        //Set port
        connectionFactory.setPort(5672);
        //Set user name
        connectionFactory.setUsername("mowen");
        //Set password
        connectionFactory.setPassword("123456");
        //Get connection (similar to jdbc)
        Connection connection = connectionFactory.newConnection();
        //Create channel
        Channel channel = connection.createChannel();
        //Declare the queue.
        //Parameter 1: queue name
        //Parameter 2: persistence (true means that the queue will still exist when the server is restarted)
        //Parameter 3: exclusive queue (the private queue that can be used by the creator and automatically deleted after disconnection)
        //Parameter 4: automatically delete the queue when all consumer clients are disconnected
        //Parameter 5: other parameters of the queue
        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);
        channel.queueDeclare(queueName3,true,false,false,null);

        //Claim switch
        channel.exchangeDeclare(exchangeName,exchangeType);

        //Queue bound to switch
        channel.queueBind(queueName1,exchangeName,"");
        channel.queueBind(queueName2,exchangeName,"");
        channel.queueBind(queueName3,exchangeName,"");

        for (int i = 0; i < 10; i++) {
            String msg="msg"+i;
            // Basic release message
            // The first parameter is the switch name
            // The second parameter is the queue mapped route key
            // The third parameter is the other properties of the message
            // The fourth parameter is the body of sending information
            channel.basicPublish(exchangeName,"",null,msg.getBytes());
        }

        channel.close();
        connection.close();
    }
}

After running, the queue in the RabbitMQ web page management background will see

Switch to Exchanges and you will see a

It's the switch we declared. Click to see the queue we bound

IV. direct switch

The direct connect switch has routing function. The queue is bound to the direct connect switch through the routing key. When sending messages, the routing key needs to be specified. When the switch receives messages, the switch will send them to the specified queue according to the routing key. The same routing key can support multiple queues.

Create a new direct class in the producer project

package com.rabbitMQ.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author mowen
 * @date  2019/11/20-11:23
 */
public class direct {
    public static void main(String[] args) throws IOException, TimeoutException {
        String exchangeName="direct";
        String exchangeType="direct";
        //Message queue name
        String queueName1="direct.queue1";
        String queueName2="direct.queue2";
        String queueName3="direct.queue3";
        //Instance connection factory
        ConnectionFactory connectionFactory=new ConnectionFactory();
        //Set address
        connectionFactory.setHost("192.168.128.233");
        //Set port
        connectionFactory.setPort(5672);
        //Set user name
        connectionFactory.setUsername("mowen");
        //Set password
        connectionFactory.setPassword("123456");
        //Get connection (similar to jdbc)
        Connection connection = connectionFactory.newConnection();
        //Create channel
        Channel channel = connection.createChannel();
        //Declare the queue.
        //Parameter 1: queue name
        //Parameter 2: persistence (true means that the queue will still exist when the server is restarted)
        //Parameter 3: exclusive queue (the private queue that can be used by the creator and automatically deleted after disconnection)
        //Parameter 4: automatically delete the queue when all consumer clients are disconnected
        //Parameter 5: other parameters of the queue
        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);
        channel.queueDeclare(queueName3,true,false,false,null);

        //Claim switch
        channel.exchangeDeclare(exchangeName,exchangeType);

        //The queue is bound to the switch and the routing key is specified
        channel.queueBind(queueName1,exchangeName,"key1");
        channel.queueBind(queueName2,exchangeName,"key2");
        channel.queueBind(queueName3,exchangeName,"key1");

        for (int i = 0; i < 10; i++) {
            String msg="msg"+i;
            // Basic release message
            // The first parameter is the switch name
            // The second parameter is the queue mapped route key
            // The third parameter is the other properties of the message
            // The fourth parameter is the body of sending information
            channel.basicPublish(exchangeName,"key1",null,msg.getBytes());
        }

        channel.close();
        connection.close();
    }
}

After running, the queue in the background will see

Switch to Exchanges and you will see

Click in

V. topic switch

The routing key of the subject switch can have certain rules. The routing key of the switch and the queue needs to adopt Format of

Separate each part

*Represents a word (not a character)

#Represents any number of words (0 or n)

New topic class in producer project

package com.rabbitMQ.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author mowen
 * @date  2019/11/20-11:23
 */
public class topic {
    public static void main(String[] args) throws IOException, TimeoutException {
        String exchangeName="topic";
        String exchangeType="topic";
        //Message queue name
        String queueName1="topic.queue1";
        String queueName2="topic.queue2";
        String queueName3="topic.queue3";
        //Instance connection factory
        ConnectionFactory connectionFactory=new ConnectionFactory();
        //Set address
        connectionFactory.setHost("192.168.128.233");
        //Set port
        connectionFactory.setPort(5672);
        //Set user name
        connectionFactory.setUsername("mowen");
        //Set password
        connectionFactory.setPassword("123456");
        //Get connection (similar to jdbc)
        Connection connection = connectionFactory.newConnection();
        //Create channel
        Channel channel = connection.createChannel();
        //Declare the queue.
        //Parameter 1: queue name
        //Parameter 2: persistence (true means that the queue will still exist when the server is restarted)
        //Parameter 3: exclusive queue (the private queue that can be used by the creator and automatically deleted after disconnection)
        //Parameter 4: automatically delete the queue when all consumer clients are disconnected
        //Parameter 5: other parameters of the queue
        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);
        channel.queueDeclare(queueName3,true,false,false,null);

        //Claim switch
        channel.exchangeDeclare(exchangeName,exchangeType);

        //The queue is bound to the switch and the routing key is specified
        channel.queueBind(queueName1,exchangeName,"com.aaa.*");
        channel.queueBind(queueName2,exchangeName,"com.*.topic");
        channel.queueBind(queueName3,exchangeName,"com.bbb.*");

        for (int i = 0; i < 10; i++) {
            String msg="msg"+i;
            // Basic release message
            // The first parameter is the switch name
            // The second parameter is the queue mapped route key
            // The third parameter is the other properties of the message
            // The fourth parameter is the body of sending information
            channel.basicPublish(exchangeName,"com.aaa.topic",null,msg.getBytes());
        }

        channel.close();
        connection.close();
    }
}

After running, the background queue will see

Switch to Exchanges and you will see

Click to enter and you will see

Topics: Java RabbitMQ JDBC Maven