Send a message using RABBITMQ simple

Source: Internet
Author: User
Tags message queue rabbitmq

Reference: http://blog.csdn.net/lmj623565791/article/details/37607165

http://blog.csdn.net/anzhsoft/article/details/19563091

Http://www.rabbitmq.com/tutorials/tutorial-one-java.html

Https://www.cnblogs.com/LiangSW/p/6218886.html

Https://www.cnblogs.com/piaolingzxh/p/5448927.html



For example, if you want to post an e-mail message, you can post it to a mailbox, then the postman gets the mail from the mailbox and delivers the message to the receiver, and in the process, RABBITMQ is similar to the mailbox, post Office, and postman, RABBITMQ is a message queue, It can receive the messages sent by the program and put them into the corresponding message queue, and some programs can get the data from the message queue to complete the communication between the programs.

Here are some concepts:


1. Producers

program, the party that sends the message is called the producer

2. Message Queuing

Used to store messages sent by producers

3. Consumers

The party that gets the message from the message queue is called the consumer






4,Connection

Connection is a TCP connection that consumers and producers connect to RABBITMQ server via TCP


5.Channel

The channel is built on top of the conection, because frequent closing of TCP connections can affect performance, so sending and receiving messages using the channel

(1) The Queuedeclare () method of the channel allows you to specify the queue to send messages/receive messages

Queue: Queues Name

Durable: Whether persistent, queue and forwarder have durable property, default is False, if RABBITMQ reboot, queue and forwarder will disappear. Set to Ture can survive this.

Exclusive: If exclusive, True indicates that it can only be accessed in this connection (the same connection).

Autodelete: Whether to delete the forwarder automatically if there is no consumer

/**
     * Declare an Exchange.
     * @see com.rabbitmq.client.AMQP.Exchange.Declare
     * @see com.rabbitmq.client.AMQP.Exchange.DeclareOk
     * @ Param exchange The name of the Exchange
     * @param type the exchange type
     * @param durable true if we are declaring A durable exchange (the exchange would survive a server restart)
     * @param autodelete True if the server should delete T He exchange when it was no longer in use
     * @param arguments other properties (construction arguments) for the exchange< c8/>* @return A declaration-confirm method to indicate the exchange is successfully declared
     * @throws java.io.IOExce Ption If an error is encountered
     *
    /Exchange.declareok Exchangedeclare (String Exchange, String type, Boolean du Rable, Boolean autodelete,
                                       map<string, object> arguments) throws IOException

(2) A message can be sent to the queue via the Basicpublish () method of the channel

Exchange: Forwarders, can pass in empty "", "" is the default forwarder

Routingkey: The routing key, depending on the routing key forwarder, determines which consumer queue the message is sent to

Body: The byte form of the message

For additional parameters, please refer to: https://www.cnblogs.com/piaolingzxh/p/5448927.html

    public void Basicpublish (string Exchange, String Routingkey, basicproperties props, byte[] body) throws IOException {
        This.delegate.basicPublish (Exchange, Routingkey, props, body);
    }

    public void Basicpublish (string Exchange, String Routingkey, Boolean mandatory, basicproperties props, byte[] body) throws IOException {
        this.delegate.basicPublish (Exchange, Routingkey, mandatory, props, body);
    }

    public void Basicpublish (string Exchange, String Routingkey, Boolean mandatory, Boolean immediate, basicproperties props, Byte[] body) throws IOException {
        this.delegate.basicPublish (Exchange, Routingkey, mandatory, immediate, props, body);
    }

6.Exchange

Forwarders, messages sent by producers are generally not delivered directly to the consumer queue, but instead use forwarders as relays, where the producer first sends the message to the forwarder, and the forwarder decides which queue to send the message to according to the routing rules. Forwarder types are direct, topic, fanout, and headers.

Here is a simple example where sender sends a message to a message queue, receiver gets a message from the message queue, the forwarder uses an empty forwarder (the default forwarder, the direct type), the queue name needs to be passed, and the forwarder takes the queue name as a routing key and sends the message to the corresponding queue.

1. Create a sender Class

Package com.rabbit.test1;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;

Import Com.rabbitmq.client.ConnectionFactory; /** * RABBITMQ Send Message * sender */public class Sender {//queue name private final static String queue_name = "Queue-t

    EST "; public static void Main (string[] argv) throws Java.io.IOException {//1. Create a connectionfactory connection factory Connectionfactor
        Y connectionfactory connectionfactory = new ConnectionFactory ();
        2. Set RABBITMQ IP information connectionfactory.sethost ("localhost") via connectionfactory; Connectionfactory.setport (5762); Specify the port//connectionfactory.setusername ("admin");//username//Connectionfactory.setpassword ("admin")
        ;//Password//3. Create a connection through connectionfactory Connection Connection Connection = Connectionfactory.newconnection ();
        4. Create a channel through connection channels channel = Connection.createchannel (); 5. Specify a queue by channel ChanneL.queuedeclare (Queue_name, False, False, false, NULL);
        The message that is sent is String: "Hello world!"; 6. Add a message to the queue through the channel, the first parameter is the forwarder, using the empty forwarder (the default forwarder, the type is direct) channel.basicpublish ("", queue_name, NULL, Message.getby
        TES ());
        SYSTEM.OUT.PRINTLN (added a message to "+ Queue_name +": "+ message);
        7. Close channel Channel.close ();
    8. Close the connection connection.close ();
 }
}

2. Recipient

Package com.rabbit.test1;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
Import Com.rabbitmq.client.ConnectionFactory;
Import Com.rabbitmq.client.QueueingConsumer;

Import Com.rabbitmq.client.QueueingConsumer.Delivery; /** * RABBITMQ Receive Message * Receiver * */public class Receiver {//queue name private final static String queue_name = "

    Queue-test "; public static void Main (string[] argv) throws Java.io.IOException, Java.lang.InterruptedException {//1. Create a Connec
        Tionfactory Connection Factory connectionfactory connectionfactory connectionfactory = new ConnectionFactory ();
        2. Set RABBITMQ IP information connectionfactory.sethost ("localhost") via connectionfactory;
        3. Create a connection via connectionfactory Connection Connection Connection = Connectionfactory.newconnection ();
        4. Create a channel through connection channels channel = Connection.createchannel (); 5. Specify queue Channel.queuedeclare via Channel (Queue_name, False, False, FAlse, NULL); 
        Unlike sending messages,//6. Create a consumer queue consumer and specify channel Queueingconsumer consumer = new Queueingconsumer (channel);
        7. Specify consumer Channel.basicconsume for channel (Queue_name, True, consumer); while (true) {//Gets the message in the queue from consumer, Nextdelivery is a blocking method and waits Delivery Delivery = Consumer if there is no content in the queue.
            Nextdelivery ();
            String message = new String (Delivery.getbody ());
        System.out.println ("received" + Queue_name + "messages:" + message);
 }

    }
}


3. Start sender to add information to the message queue


By accessing the RABBITMQ management interface, you can see that a queue-test queue is created automatically and there is a message


Starting reciever, you can see that the recipient gets the message from the message queue and prints it in the console



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.