Simple Mode Quick Start for RabbitMQ and Handling Timeout Exceptions

This article is for JAVA newcomers who want to know about RabbitMQ and who don't want to see the official website documents (headaches for English water viewers (), but suggest that you have the ability or the ability to see the official website documents).

Message Queue MQ (1)

MQ is all called Message Queue, and Message Queuing is the method of communication between applications and applications.

First, introduce some common communication schemes.

Why use MQ?

In a project, some time-consuming operations that do not require immediate return can be extracted for asynchronous processing, which greatly saves the server's request response time and thus improves the throughput of the system.

In development, message queues typically have the following scenarios:

Apply decoupling, asynchronous processing (to improve system response speed), flow peaking (peak stacking messages, continue processing messages after peak), log processing (distributed logs, generally kafka), pure communication.

 

AMQP and JMS

MQ is the model of message communication; there are approximately two main ways to implement MQ: AMQP, JMS.

AMQP

AMQP Advanced Message Queuing Protocol is a network protocol that delivers asynchronous messages between processes, more precisely a binary wire-level protocol.This is the essential difference between AMQP and JMS. AMQP is not defined from the API layer, but directly defines the data format for network exchange.

JMS

JMS, the Java Message Service application interface, is a Java platform API for Message-Oriented Middleware (MOM), which is used to send messages between two applications or in a distributed system for asynchronous communication.

Differences between AMQP and JMS

JMS defines a unified interface to unify message operations; AMQP unifies data interaction formats by specifying protocols

JMS restricts the use of the Java language; AMQP is a protocol and does not specify how it is implemented, so it is cross-lingual.

JMS specifies two message modes; AMQP has more.

Message Queuing Products: The mature and mainstream MQs on the market are Kafka, RocketMQ, RabbitMQ. This paper mainly introduces the use of RabbitMQ.

An open source message queue written in Erlang (language) supports many protocols: AMQP, XMPP, SMTP,STOMP, which makes it very heavy and more suitable for enterprise development.At the same time, the Broker architecture was implemented. The core idea was that producers would not send messages directly to the queue, and messages would be queued in the central queue first when sent to the client.Good support for routing, load balancing, and data persistence.It is mostly used for enterprise-level ESB integration.

Introduction to RabbitMQ

RabbitMQ, developed by erlang language, is a message queue based on AMQP (Advanced Message Queue Advanced Message Queue Protocol), which is a communication method between applications. Message queue is widely used in distributed system development.

RabbitMQ official address: http://www.rabbitmq.com/

RabbitMQ offers six modes: simple mode, work queue (cluster) mode, Publish/Subscribe publishing and subscription (broadcasting of switches), Routing (directed to switches) routing mode, Topics topic (flexible routing) mode, RPC remote invocation mode (remote invocation, not much MQ; no introduction); and //brackets are your own way of understanding for reference only.You can go to the official introduction for details.

Introducing the corresponding modes of the official website: https://www.rabbitmq.com/getstarted.html

Install RabbirMQ

Two ways: windows and Linux (skipped here)

I am version 3.6.10 installed on Linux CenOS 6.7

Startup success refers to the following two figures

Manage users first on the WEB page

Role description: Tags

1. Super Administrator

You can log on to the administration console, view all information, and operate on users, policies.

2. Monitor

You can log in to the administration console and view information about the rabbitmq node (number of processes, memory usage, disk usage, etc.)

3. Policy Maker: You can log on to the Administration Console and manage the policy at the same time.However, you cannot view the information about the node (the part identified by the red box above).

4. General Manager: can only log on to the management console, can not see the node information, and can not manage the strategy.

5. Others: Can't log on to the management console, usually ordinary producers and consumers.

Virtual Hosts Configuration

In RabbitMQ, you can virtual message server Virtual Host, where each Virtual Host corresponds to a relatively independent RabbitMQ server and each VirtualHost is isolated from each other.exchange, queue, message cannot communicate.db equivalent to mysql.Virtual Name generally starts with/

Add a queue, where you need to combine the top and bottom diagrams

User's password needs to be changed

View the default switch

Common ports

RabbitMQ Getting Started

Goal: The starter case will use RabbitMQ's simple mode to implement the communication process.

1. Create a Maven project by first adding a dependency on pom.xml.

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6     <groupId>com.jxjdemo</groupId>
 7     <artifactId>rabbitmq1_demo</artifactId>
 8     <version>1.0-SNAPSHOT</version>
 9 
10     <dependencies>
11         <dependency> <!--rabbitmq Dependency on-->
12             <groupId>com.rabbitmq</groupId>
13             <artifactId>amqp-client</artifactId>
14             <version>5.6.0</version>
15         </dependency>
16     </dependencies>
17 </project>

2. New producer class, production sends message

 1 package com.jxjdemo.mq.simple;
 2 
 3 import com.rabbitmq.client.Channel;
 4 import com.rabbitmq.client.Connection;
 5 import com.rabbitmq.client.ConnectionFactory;
 6 
 7 public class SimpleProducer {
 8     public static void main(String args[]) throws Exception{
 9 //1,Create Link Factory Object-factory=newConnectionFactory(). Create links with
10         ConnectionFactory factory = new ConnectionFactory();
11 
12 //2,Set up RabbitMQ Service Host Address, Default localhost-factory.setHost("localhost")
13         factory.setHost("192.168.211.128");
14 //3,Set up RabbitMQ Service Port, Default-1-factory.setPort(5672)
15         factory.setPort(5672);
16 //4,Set virtual host name, default/-factory.setVirtualHost("szitheima")
17          factory.setVirtualHost("shujuku1122");
18 //5,Set user connection name, default guest-factory.setUsername("admin")
19         factory.setUsername("admin");
20 //6,Set link password, default guest-factory.setPassword("admin")
21         factory.setPassword("123456");
22  //      factory.setConnectionTimeout(5000);
23 //        factory.setWorkPoolTimeout(5000);
24 //        factory.setHandshakeTimeout(5000);
25 //7,create link-connection=factory.newConnection()
26         Connection connection = factory.newConnection(); //Error, throw exception
27 //8,Create Channel-channel=connection.createChannel()
28         Channel channel = connection.createChannel();
29 //9,Declare Queue-channel.queueDeclare(Name, whether persisted ( true Save Hard Disk, Read and Delete), Is this connection exclusive,Whether to delete automatically(false Read and Delete),Additional parameters)
30         channel.queueDeclare("simplequeue", true, false, false, null);
31 //10,Create message-Stringm=xxx
32         String msg = "This is the first time we have sent MQ news";
33 //11,message sending-channel.basicPublish(Switch[default DefaultExchage],Route key[Simple mode can pass queue name],Message Other Properties,Message Content)
34         channel.basicPublish("", "simplequeue", null, msg.getBytes("utf-8"));
35 //12,close resource-channel.close();connection.close()
36         channel.close();
37        connection.close();
38     }
39 }

A message was sent after execution and no exceptions were seen.

Extension: Exceptions encountered here are, time-out

Solution 1:

When sending an unsuccessful error, restart the MQ first and restart the IDE in Administrator's Way. This is generally a problem with MQ.

Send message is empty, message cannot have spaces.Note the library name.

Solution 2:

Our system installation will give the system a name as a result: the modified hostname is not in the hosts file of the linux system, so when parsing, it cannot be obtained directly from the file, and multiple parsing is required to resolve the hostname.

Different linux versions, this profile may also be different vim/etc/hosts

Continue to say what was successful.

3. Create consumers and receive messages.

 1 package com.jxjdemo.mq.simple;

 2 
 3 import com.rabbitmq.client.*;
 4 
 5 import javax.security.auth.callback.Callback;
 6 import java.io.IOException;
 7 import java.util.concurrent.TimeoutException;
 8 
//Document comment deleted here
16 public class SimpleConsumer { 17 public static void main(String args[]) throws IOException, TimeoutException { 18 //1,Create Link Factory Object-factory=newConnectionFactory() 19 ConnectionFactory factory = new ConnectionFactory(); 20 //2,Set up RabbitMQ Service Host Address, Default localhost-factory.setHost("localhost") 21 factory.setHost("192.168.211.128"); 22 //3,Set up RabbitMQ Service Port, Default-1-factory.setPort(5672) 23 factory.setPort(5672); 24 //4,Set virtual host name, default/-factory.setVirtualHost("szitheima") 25 factory.setVirtualHost("shujuku1122"); 26 //5,Set user connection name, default guest-factory.setUsername("admin") 27 factory.setUsername("admin"); 28 //6,Set link password, default guest-factory.setPassword("admin") 29 factory.setPassword("123456"); 30 //7,create link-connection=factory.newConnection() 31 Connection connection = factory.newConnection(); 32 //8,Create Channel-channel=connection.createChannel() 33 Channel channel = connection.createChannel(); 34 //9,Declare Queue-channel.queueDeclare(Name, persistence, exclusive connection,Whether to delete automatically,Additional parameters) 35 channel.queueDeclare("simplequeue",true ,false , false,null ); 36 //10 receive messages 37 Consumer callback = new DefaultConsumer(channel){ 38 /** 39 * @param consumerTag Consumer label, which can be specified when channel.basicConsume 40 * @param envelope Envelopes, contents of message packages, from which message id s, message routingkey s, switches, message and retransmit flags can be obtained (do you need to resend after receiving a message fails) 41 * @param properties Attribute information (specified when the producer sends it) 42 * @param body Message Content 43 * @throws IOException 44 */ 45 @Override 46 public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { 47 Long deliveryTag = envelope.getDeliveryTag(); //news ID 48 String exchange = envelope.getExchange(); 49 String routingKey = envelope.getRoutingKey(); //Route KEY 50 //Message Content 51 String msg = new String(body,"utf-8"); 52 System.out.println( 53 "routingKey:" + routingKey + 54 "routingKey:" + routingKey + 55 ",exchange:" + exchange + 56 ",deliveryTag:" + deliveryTag + 57 ",message:" + msg); 58 } 59 }; 60 channel.basicConsume("simplequeue", callback); 61 //Do not close, continue accepting messages 62 } 63 }

See the results after execution

When your code runs here, congratulations on getting started.

This time comes here for the time being.For the other four modes, break them down slowly next time.

Keywords: Java RabbitMQ Maven Linux

Added by fabiuz on Sat, 23 Nov 2019 21:59:06 +0200