RabbitMQ-from basic to practice (1)-Hello RabbitMQ, rabbitmq-rabbitmq

Source: Internet
Author: User

RabbitMQ-from basic to practice (1)-Hello RabbitMQ, rabbitmq-rabbitmq
1. Introduction

This article introduces how to install the RabbitMQ Server on windows and use JAVA code to send and receive messages.

2. Install RabbitMQ

After Windows is installed

3. Enable the RabbitMQ Web Console

RabbitMQ provides a console for managing and monitoring RabbitMQ, Which is disabled by default. You need to run the following command to start

At present, you can ignore this interface, which will be detailed later, or you can view the official documentation here.

4. Compile MessageSender

Spring has encapsulated RabbitMQ. Normally, Spring integration is used. In the first project, we will not consider so many

Create a Maven project in IDE and paste the following dependency in pom. xml. The latest version of RabbitMQ dependency can be found here.

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

After the Maven download is complete, you can see the JAR of RabbitMQ in Maven Dependencies.

Here, we found that the RabbitMQ log depends on the slf4j-api package, the slf4j-api is not a log implementation, this is unable to output the log, So we add a log implementation to the pom, logback is used here.

<dependency>    <groupId>ch.qos.logback</groupId>    <artifactId>logback-classic</artifactId>    <version>1.2.1</version></dependency>

The maven dependency is as follows, so you can rest assured to write code.

Create a MessageSender class. The Code is as follows:

1 import java. io. IOException; 2 import java. util. concurrent. timeoutException; 3 4 import org. slf4j. logger; 5 import org. slf4j. loggerFactory; 6 7 import com. rabbitmq. client. channel; 8 import com. rabbitmq. client. connection; 9 import com. rabbitmq. client. connectionFactory; 10 11 public class MessageSender {12 13 private Logger logger = LoggerFactory. getLogger (MessageSender. class); 14 15 // declare a queue name 16 priv Ate final static String QUEUE_NAME = "hello"; 17 18 public boolean sendMessage (String message) {19 // new A RabbitMQ connection factory 20 ConnectionFactory factory = new ConnectionFactory (); 21 // set the RabbitMQ address to be connected, which points to the 22 factory of the local machine. setHost ("127.0.0.1"); 23 Connection connection = null; 24 Channel channel = null; 25 try {26 // try to get a Connection 27 connection = factory. newConnection (); 28 // try to create a channel29 channel = connection. create Channel (); 30 // The parameters here are described later in 31 channels. queueDeclare (QUEUE_NAME, false, null); 32 // note that getBytes () is called here, which actually sends a byte array. After the receiver receives the message, it needs to be re-assembled into String33 channel. basicPublish ("", QUEUE_NAME, null, message. getBytes (); 34 logger.info ("Sent" + message + "'"); 35 // close the channel and connect to 36 channels. close (); 37 connection. close (); 38} catch (IOException | TimeoutException e) {39 // logs are logged upon failure. If false is returned, the sending failure is 40 logger. error ("Send message faild! ", E); 41 return false; 42} 43 return true; 44} 45}

Then, call sendMessage in the main method of the App class.

1 public class App {2     public static void main( String[] args ){3         MessageSender sender = new MessageSender();4         sender.sendMessage("hello RabbitMQ!");5     }6 }

Print the following logs:

Open the RabbitMQ console and you can see that the message has been in RabbitMQ.

Click in and use the getMessage function provided by the console. You can see that the message has been successfully managed by RabbitMQ.

At this point, MessageSender has been written. In lines 31 and 33 of this class, we call the queue declaration and message sending respectively.

channel.queueDeclare(QUEUE_NAME, false, false, false, null);channel.basicPublish("", QUEUE_NAME, null, message.getBytes());

QueueDeclare has many parameters. Let's take a look at his source code and have a detailed explanation on the annotations. I have simply translated it.

1/** 2 * Declare a queue declares a queue 3 * @ see com. rabbitmq. client. AMQP. queue. declare 4 * @ see com. rabbitmq. client. AMQP. queue. declareOk 5 * @ param queue the name of the queue name 6 * @ param durable true if we are declaring a durable queue (the queue will keep ve a server restart) is persistent, if this parameter is set to true, the system will survive 7 * @ param exclusive after rabbitMQ is restarted. if we are declaring an exclusive queue (restricted to this connection ), valid only for the current connection. After the current connection is disconnected, the queue is deleted (persistence and deletion are set) 8 * @ param autoDelete true if we are declaring an autodelete queue (server will delete it when no longer in use) is automatically deleted, empty queue 9 * @ param arguments other properties (construction arguments) When no consumer has subscribed) for the queue other parameters 10 * @ return a declaration-confirm method to indicate the queue was successfully declared11 * @ throws java. io. IOException if an error is encountered12 */13 Queue. declareOk queueDeclare (String queue, boolean durable, boolean exclusive, boolean autoDelete, 14 Map <String, Object> arguments) throws IOException;

The first four parameters are very easy to understand. The last one is "other parameters". What are the other parameters? This is really hard to find. Please explain it again. The official documentation is as follows:

  • TTL Time To Live survival Time
  • Dead Lettering's last words: What do I do when a message dies?
  • Length Limit
  • Priority Queues Priority
5. Compile MessageConsumer

Create a Maven project MessageConsumer to separate it from Sender.

1 package com. liyang. ticktock. rabbitmq; 2 3 import java. io. IOException; 4 import java. util. concurrent. timeoutException; 5 6 import org. slf4j. logger; 7 import org. slf4j. loggerFactory; 8 9 import com. rabbitmq. client. AMQP; 10 import com. rabbitmq. client. channel; 11 import com. rabbitmq. client. connection; 12 import com. rabbitmq. client. connectionFactory; 13 import com. rabbitmq. client. consumer; 14 import com. ra Bbitmq. client. defaultConsumer; 15 import com. rabbitmq. client. envelope; 16 17 public class MessageConsumer {18 19 private Logger logger = LoggerFactory. getLogger (MessageConsumer. class); 20 21 public boolean consume (String queueName) {22 // connect RabbitMQ23 ConnectionFactory factory = new ConnectionFactory (); 24 factory. setHost ("127.0.0.1"); 25 Connection connection = null; 26 Channel channel = null; 27 try {28 Connection = factory. newConnection (); 29 channel = connection. createChannel (); 30 // when the queue is declared here to retrieve messages, the queue will certainly have 31 // note that queueDeclare is idempotent, that is, the consumer and producer, no matter who declares it first, there will be only one queue32 channel. queueDeclare (queueName, false, null); 33 34 // here, the handleDelivery method of DefaultConsumer is rewritten, because the getByte () method is used to send the message (), here we need to reassemble it into String35 Consumer consumer = new DefaultConsumer (channel) {36 @ Override37 public void handleDe Livery (String consumerTag, Envelope envelope, AMQP. basicProperties properties, byte [] body) 38 throws IOException {39 String message = new String (body, "UTF-8 "); 40 logger.info ("received'" + message + "'"); 41} 42}; 43 // The above is a declared consumer, here, the declared consumer is used to consume the message 44 channel in the queue. basicConsume (queueName, true, consumer); 45 46 // The connection cannot be closed. After the consumption method is called, the consumer will always connect to rabbitMQ waiting for consumption 47 48} catch (IOException | TimeoutException e) {49 // Error Logs are recorded after the failure, and false is returned, indicating that the consumption failed 50 logger. error ("send message faild! ", E); 51 return false; 52} 53 54 55 return true; 56} 57}

Then, call Cunsumer in the main method of the App for consumption.

1 public class App 2 {3 // The queue name must be the same as the name in the producer; otherwise, the queue 4 private final static String QUEUE_NAME = "hello" cannot be found "; 5 6 public static void main (String [] args) 7 {8 MessageConsumer consumer = new MessageConsumer (); 9 consumer. consume (QUEUE_NAME); 10} 11}

The result is as follows: the consumer is waiting for the message. Every time a message comes in, it will be consumed immediately.

6. Multiple consumers consume one queue at a time

Modify the Consumer

Create multiple consumers in the App

Modify the Sender so that it keeps sending messages to RabbitMQ.

Start Sender

Start Consumer and find that the messages are evenly sent to four clients, one for each, and no one is in the queue.

What if we speed up? Remove the Sender's rest time and find that the consumption starts to become irregular.

7. Conclusion

The first chapter is over. This chapter describes how to use the JAVA language to compile producers and consumers.

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.