Rabbit MQ simple pattern Hello World

First, look at the introduction of the official website in a simple mode

Official website: https://www.rabbitmq.com/tutorials/tutorial-one-java.html

RabbitMQ is a message broker: it accepts and forwards messages. You can think of it as a post office: when you put the message you want to publish in the mailbox, you can ensure that Mr. or Ms. mailpherson will finally deliver the message to the recipient. By analogy, this mode is: RabbitMQ is a mailbox, a post office and a postman.

Officials say: if you can't receive a message, it may be: by default, it needs at least 200 MB of free space.

Nothing else.

Well, let's start our logic

Firstly, the simple pattern is divided into three roles: a producer, a consumer and a message middleware

The producer produces messages and sends them to MQ through AMQP protocol, and then the consumer obtains messages from MQ through AMQP protocol.

send message

  • Create connection factory object
  • Set some parameters for the factory object
  • Create connection with factory
  • Get queues through connections (specify the properties of some queues)
  • Sending messages through queues
  • Release resources

receive messages

  • Create connection factory object
  • Set some parameters for the factory object
  • Create connection with factory object
  • Get queue through connection (specify some queue properties)
  • When creating a consumer, you can write a callback function to select whether to use the callback function
  • Get message
  • No resources need to be released

Content of Middleware

RabbitMQ: provide the switch (which can be understood as database / govbuy), provide the account and password that can be connected, and can log in remotely. This is done through the visual interface.

Start looking at the code

The first is Maven's code

 <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.6.0</version>
        </dependency>

Producer code

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

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

public class provider {
    public static void main(String[] args) throws IOException, TimeoutException {

        //Remember to refresh Maven simple mode. There is no switch, but the default switch will be used


        //1 create connection factory
        ConnectionFactory factory = new ConnectionFactory();

        //2 set parameters
        factory.setHost("118.31.127.248");  //127.0.0.0.1 without setting
        factory.setPort(5672);              //If it is not set, it will be 5672
        factory.setVirtualHost("/govbuy");  //Default virtual machine without setting/
        factory.setUsername("zanglikun");   //If it is not set, it is the default guest
        factory.setPassword("zanglikun");   //If it is not set, it is the default guest

        //3 create Connection
        Connection connection = factory.newConnection();

        //4 get chanl
        Channel channel = connection.createChannel();

        //5 create a Queue. If there is no Queue, it is called hello_ The world Queue will be created automatically
        /*
        Parameters:
            1:  queue Queue name
            2:  durable Do you want to persist the data in erlang's own database? The restart data still exists
            3:  exclusive Exclusive only one consumer is allowed to listen to this queue 2. When connecting, whether to delete the queue is generally flag
            4:  autodelete Delete automatically? When there is no consumer, it will be deleted automatically
            5:  arguement Parameter: how to delete a queue parameter
         */
        channel.queueDeclare("hello_world",true,false,false,null);

        //6 send message to
        /*
        Parameters:
            1: exchange Switch name. Simple mode, the default
            2: routingKey Route name
            3: props configuration information
            4: body Real sent data
         */

        String Body = "Hello Rabbit MQ";


        //Simple mode has no switch, so the route is the same as the queue name

        channel.basicPublish("","hello_world",null,Body.getBytes());
        System.out.println("Sent on:"+System.currentTimeMillis());
        //7 release resources
        channel.close();
        connection.close();

    }
}

Consumer code

import com.rabbitmq.client.*;

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

public class consumer {
    public static void main(String[] args) throws IOException, TimeoutException {

        //Remember to refresh Maven simple mode. There is no switch, but the default switch will be used


        //1 create connection factory
        ConnectionFactory factory = new ConnectionFactory();

        //2 set parameters
        factory.setHost("118.31.127.248");  //127.0.0.0.1 without setting
        factory.setPort(5672);              //If it is not set, it will be 5672
        factory.setVirtualHost("/govbuy");  //Default virtual machine without setting/
        factory.setUsername("zanglikun");   //If it is not set, it is the default guest
        factory.setPassword("zanglikun");   //If it is not set, it is the default guest

        //3 create Connection
        Connection connection = factory.newConnection();

        //4 get chanl
        Channel channel = connection.createChannel();


        //5 this method does not require parameters. It is generated by adding method block {} and ALT + inster -- > override methods
        Consumer consumer = new DefaultConsumer(channel){
            // This is a callback method that will be executed automatically when a message is received.
            /**
             *
             * @param consumerTag identification
             * @param envelope  Get some information, switch, routing Key
             * @param properties configuration information
             * @param body  Real data
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("Received at:"+System.currentTimeMillis());
                System.out.println("consumerTag: "+consumerTag);
                System.out.println("Exchange: "+envelope.getExchange());
                System.out.println("RoutingKey: "+envelope.getRoutingKey());
                System.out.println("properties: "+properties);
                System.out.println("body: "+new String(body));
                System.out.println();
            }
        };


        //6 get message
        /*
            parameter
                1: queue Queue name
                2: Auto ack Auto confirm
                3: callback callback object 

         */
        channel.basicConsume("hello_world",true,consumer);


        // The consumer does not need to close the connection because it needs to listen to MQ.

    }
}

Start the producer first because the producer created the queue hello_world queue

Otherwise, the consumer will burst the exception that the queue is not found in the virtual machine

Emphasize that consumers do not need to close connections and release resources.

Special instructions: The brilliance of solving problems hides the pain of knocking bugs. All things enter samsara, and no one can escape! The above articles are my actual operation and written notes. There will be no full-text embezzlement of other people's articles! Please don't embezzle directly!

Added by dzysyak on Fri, 14 Jan 2022 04:24:05 +0200