AAA RABBITMQ with Java, spring combination of examples in detail

Source: Internet
Author: User
Tags rabbitmq

Lin Bingwen Evankaka Original works. Reprint please indicate the source Http://blog.csdn.net/evankaka

Summary: This article describes RABBITMQ, which provides a way to install the RABBITMQ service under Ubuntu. It is best to demonstrate how to use RABBITMQ with two examples of RABBITMQ and Java, Spring.

This project is free to download


introduction of RABBITMQ

1.1, the advantages of RABBITMQ (scope of application)
1. The development of Erlang language has the advantages of high availability and high concurrency, and is suitable for cluster servers.
2. Robust, stable, easy-to-use, cross-platform, support multiple languages, complete documentation.
3. There is a message recognition mechanism and persistence mechanism, high reliability.
4. Open source
Advantages of other MQ:
1. Apache ACTIVEMQ has the highest exposure rate, but may lose messages.
2. ZEROMQ latency is low and supports flexible topologies, but message persistence and crash recovery are not supported.

1.2. Several concept descriptions
Producer&consumer
Producer refers to the message producer, consumer the consumer of the message.
Queue
Message Queuing, which provides a FIFO processing mechanism with the ability to cache messages. RABBITMQ, queue messages can be set to persist, temporarily, or automatically deleted.
Set to persistent queues, messages in the queue are stored on the server's local hard drive to prevent system crash and data loss
Set as temporary queue, data in queue is lost after system restarts
Set to automatically delete queues, when no user is connected to the server, the data in the queue is automatically deleted Exchange

Exchange is similar to a switch in a data communication network and provides a message routing policy. In RABBITMQ, producer send messages directly to the queue instead of through a channel, but first send it to exchange. One exchange can bind to multiple queue, and producer passes a message passing a routing_key,exchange that routes the message to the specified queue according to the Routing_key according to the particular routing algorithm. As with queue, Exchange can be set to persistent, temporarily or automatically deleted.
There are 4 types of exchange: Direct (default), Fanout, topic, and headers, and the different types of exchange forwarding messages differ in their policies:
Direct
A direct exchanger that works like a unicast and exchange sends messages exactly to match Routing_key's queue
Fanout
A broadcast is a type exchanger, and exchange forwards messages to all bound queue regardless of the Routing_key setting for the message.
Topic
Theme exchanger, which works like a multicast, Exchange sends messages forward and Routing_key all queues that match the pattern, for example, Routing_key User.stock message is forwarded to the bind matching pattern as *. stock, User.stock, *. * and #.user.stock. #的队列. (* The table matches a random phrase, #表示匹配0个或多个词组)
Headers
Header match for message body (ignore)
Binding
Binding is the binding of a particular Exchange to a particular Queue. The bindings of Exchange and queue can be many-to-many relationships.
Virtual Host
On the RABBITMQ server, you can create multiple virtual message broker, also known as "virtual hosts" (vhosts). Each vhost is essentially a MINI-RABBITMQ server that manages its own exchange, and bindings respectively. Vhost is equivalent to a physical server that provides boundary isolation for different apps, enabling applications to run safely on different vhost instances without interfering with each other. Producer and consumer Connections Rabbit server needs to specify a vhost.

1.3, the use of Message Queuing process
1. The client connects to the Message Queuing server and opens a channel.
2. The client declares an exchange and sets the related properties.
3. The client declares a queue and sets the related properties.
4. The client uses routing key to establish a binding relationship between Exchange and queue.
5. Clients post messages to exchange.
6. When Exchange receives the message, it routes messages to one or more queues based on the key of the message and the binding that has been set.


Second, the environment configuration and installation

1, Erlang Environment installation
The RABBITMQ is based on Erlang, so you must first configure the Erlang environment.
Download the latest Erlang installation package from Erlang's official website http://www.erlang.org/download.html, the version i downloaded is otp_src_R14B03.tar.gz. And then:

$ tar xvzf otp_src_R14B03.tar.gz
$ cd otp_src_r14b03
$/configure
Post-compilation output
The following figure:


Note:
May be an error configure:error:No curses library functions found
Configure:error:/bin/sh '/home/liyixiang/erlang/configure ' failed for ERTs


The reason is the lack of ncurses package resolution: Under the Ubuntu system

Apt-cache Search ncurses
apt-get Install Libncurses5-dev

And then re-execute

./configure

Tip There is no wxwidgets and FOP, SSH, ODBC, SSL, but the problem is small. Go on:

Make

And then:

sudo make install


Configuring Erlang Environment variables
Modify the/etc/profile file to add the following environment variables: (Vim profile I insert edit complete ESC exit wq! Force Modify)

#set Erlang Environment
export path= $PATH:/usr/erlang/bin: $PATH
Source profile to make the file effective

Here's my


2, Rabbitmq-server installation

After installing Erlang, start installing Rabbitmq-server. The installation method has three kinds, here the author all three tried, only the following this method succeeded.

Direct use:

Apt-get  Install Rabbitmq-server

Automatically opens when the installation is complete:

To view RABBITMQ running status by using a command:

Rabbitmqctl status


Stop it

Rabbitmqctl stop

Open

Rabbitmq-server start

3, RABBITMQ Web Management page Plug-in installation

Enter the following command

cd/usr/lib/rabbitmq/bin/
rabbitmq-plugins Enable Rabbitmq_management

Here the author has been installed unsuccessfully.


If the installation successfully opens the browser, input http://[server-name]:15672/such as http://localhost:15672/, will require the user name and password, with the default guest/guest can be (guest/ The guest user can only log on from the localhost address, and if you want to configure remote logins, you must create a different user.
If you want to do it from Telnet. Security considerations, Guest This default user only through http://localhost:15672 to log in, other IP can not directly use this Guest account. Here we can use the configuration file to implement from the remote login management interface, as long as the edit/etc/rabbitmq/rabbitmq.config file (not added), add the following configuration on it.

4, add Users

Vim/etc/rabbitmq/rabbitmq.config
And then add
[ 
{rabbit, [{tcp_listeners, [5672]}, {loopback_users, [' ASDF ']}]} 
.
Look, there's a dot on the top.

Now you have added a new authorized user, ASDF, to use this username remotely. Remember to use the command to add this command first:
cd/usr/lib/rabbitmq/bin/
#用户名与密码
sudo rabbitmqctl add_user asdf 123456
User is set to administrator for remote access
sudo rabbitmqctl set_user_tags asdf Administrator 
sudo rabbitmqctl set_permissions-p/asdf ". *" ". *" ". *"

In fact, you can also use the Management Platform page to add users and passwords and other information directly. If you do not have remote access or Telnet check is not 5672, 15672 ports are not open ...

5. Open port

UFW Allow 5672


Three, simple Java instanceHere's a simple example of using Java: 1, first, the base class of the message producer and provider
Package Com.lin;

Import java.io.IOException;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
 
Import Com.rabbitmq.client.ConnectionFactory;
     
    /** * * Feature Summary: EndPoint type of queue * * @author Linbingwen * @since January 11, 2016 * * Public abstract class endpoint{
    protected Channel Channel;
    protected Connection Connection;
     
    protected String endpointname;
         
         Public EndPoint (String endpointname) throws ioexception{this.endpointname = Endpointname;
         
         Create a connection factory connectionfactory factory = new ConnectionFactory ();
         Hostname of your RABBITMQ server Factory.sethost ("10.75.4.25");
         Factory.setport (5672);
         Factory.setusername ("asdf");
         
         Factory.setpassword ("123456");
         
         Getting a connection connection = Factory.newconnection ();
     Creating a Channel Channel = Connection.createchannel ();    
         Declaring a queue for this channel.
         If queue does not exist,//it is created on the server.
    Channel.queuedeclare (Endpointname, False, False, false, NULL); /** * Closes channel and connection.
     is not necessary because the implicit invocation is automatic.
         * @throws IOException */public void Close () throws ioexception{This.channel.close ();
     This.connection.close (); }
}

2. Message provider
Package com.lin.producer;

Import java.io.IOException;
Import java.io.Serializable;

Import Org.apache.commons.lang.SerializationUtils;

Import Com.lin.EndPoint;
 
 
/**
 * * 
 feature Summary: Message producer
 * * 
 @author linbingwen
 * @since  January 11, 2016
/public class Producer extends endpoint{public
     
    Producer (String endpointname) throws ioexception{
        super (endpointname);
    Public
 
    void SendMessage (Serializable object) throws IOException {
        channel.basicpublish ("", Endpointname, NULL, Serializationutils.serialize (object));
    }  

3. News Consumer
Package Com.lin.consumer;
Import java.io.IOException;
Import Java.util.HashMap;

Import Java.util.Map;

Import Org.apache.commons.lang.SerializationUtils;
Import Com.lin.EndPoint;
Import com.rabbitmq.client.AMQP.BasicProperties;
Import Com.rabbitmq.client.Consumer;
Import Com.rabbitmq.client.Envelope;
 
 
Import com.rabbitmq.client.ShutdownSignalException; /** * * Feature Summary: Read the queue of the program end, implementation of the Runnable interface * * * @author Linbingwen * @since January 11, 2016 * * * public class Queueconsumer Exte
        NDS EndPoint implements Runnable, consumer{public Queueconsumer (String endpointname) throws ioexception{       
    Super (Endpointname); public void Run () {try {//start consuming messages.
            Auto acknowledge messages.
        Channel.basicconsume (Endpointname, true,this);
        catch (IOException e) {e.printstacktrace ();
     }/** * Called when consumer is registered. */public void Handleconsumeok (String consumeRtag) {System.out.println ("Consumer" +consumertag + "registered");
     }/** * Called when the new message is available.  */public void Handledelivery (String consumertag, Envelope env, basicproperties props, byte[] body) throws
        IOException {Map map = (HASHMAP) serializationutils.deserialize (body);
 
    SYSTEM.OUT.PRINTLN ("message number" + map.get ("message number") + "received."); public void Handlecancel (string consumertag) {} public void Handlecancelok (string consumertag) {} public void hand Lerecoverok (String consumertag) {} public void Handleshutdownsignal (string consumertag, Shutdownsignalexception arg1) {}
}

4, testing
Package com.lin.test;
Import java.io.IOException;
Import java.sql.SQLException;

Import Java.util.HashMap;
Import Com.lin.consumer.QueueConsumer;
 
Import Com.lin.producer.Producer; public class Test {public Test () throws exception{queueconsumer consumer = new Queueconsumer ("Queu
        E ");
        Thread consumerthread = new Thread (consumer);
         
        Consumerthread.start ();
         
        Producer Producer = new Producer ("queue");
            for (int i = 0; i < 1000000 i++) {HASHMAP message = new HashMap ();
            Message.put ("message number", I);
            Producer.sendmessage (message);
        SYSTEM.OUT.PRINTLN ("message number" + i + "sent."); }/** * @param args * @throws SQLException * @throws ioexception/public static
    void Main (string[] args) throws exception{new Test (); }
}
The jar package introduced:
<!--RABBITMQ client-->
	<dependencies>
		<dependency>
			<groupid>com.rabbitmq</ groupid>
			<artifactId>amqp-client</artifactId>
			<version>3.0.4</version>
		</dependency>
	
	<dependency>
		<groupId>commons-lang</groupId>
		<artifactid >commons-lang</artifactId>
		<version>2.6</version>
	</dependency>
	< dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3< /artifactid>
		<version>3.1</version>
	</dependency>
	</dependencies>

Test results: When providing messages in consumer messages
Then open the RABBITMQ server at the same time and enter the following:

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.