Java Use RABBITMQ sample

Source: Internet
Author: User
Tags message queue rabbitmq download rabbitmq
RABBITMQ Introduction

RABBITMQ is a popular message agent, typically used for integration between applications or between different components of a program through messages. It has the advantage of high availability and high concurrency, and is suitable for cluster servers. Implemented in Erlang with client-side support for the main programming languages. RABBITMQ Environment Configuration environment configuration under Linux

I'm using the CentOS 6.5 version.

Download the installation package from this address first

Download Address

$ TAR-ZXVF otp_src_18.3.tar.gz 

$ cd otp_src_18.3

$./configure--prefix=/usr/local/erlang--with-ssl- Enable-threads-enable-smmp-support-enable-kernel-poll--enable-hipe--without-javac

$ make

$ sudo Install

Configure Environment variables

Vim/etc/profile

Add the following text at the end of the file:

Erlang_home=/usr/local/erlang
path= $ERLANG _home/bin: $PATH
export erlang_home
export PATH

Make environment variables effective

Source/etc/profile

Then download RABBITMQ, download the address

Install dependencies First

$ sudo yum install Xmlto
$ xz-d rabbitmq-server-generic-unix-3.6.1.tar.xz

$ tar-xvf rabbitmq-server-generic-unix-3.6.1.tar 

# Move Directory
$ sudo cp-rf./RABBITMQ_SERVER-3.6.1//usr/local/

$ cd/usr/local

#改名字
$  mv Rabbitmq_ server-3.6.1 rabbitmq-3.6.1

# Install Web admin plug-in
$ cd sbin/

$./rabbitmq-plugins Enable Rabbitmq_management

Starting and shutting down services

$./rabbitmq-server

# Background boot
$./rabbitmq-server-detached

# Close
$/rabbitmqctl Stop

Log on to the Web admin side

Start RABBITMQ, and then the browser enters
http://10.0.0.221:15672/

This IP address is the IP of the host you actually install, please modify it according to the actual situation.

Configure login account below

$./rabbitmqctl add_user pony 123456
Creating user "Pony"

... $./rabbitmqctl set_user_tags Pony Administrator       
Setting tags for user "pony" to [Administrator] ...

Refresh, log in with the account you just created, as follows:

It is important to note that if the host is equipped with a firewall, the port to be used is open

-A input-p tcp-m State--state new-m TCP--dport 15672-j ACCEPT
-A input-p tcp-m State--state new-m TCP--dpor T 25672-j ACCEPT
-a input-p tcp-m state--state new-m TCP--dport 5672-j ACCEPT
-a input-p tcp-m state--st Ate new-m tcp--dport 4369-j ACCEPT
-A input-p tcp-m State--state new-m TCP--dport 5671-j
environment configuration under Windows

Erlang Download Address

RABBITMQ Download Address

You can download the version you need according to your needs, I download here are:

Otp_win64_18.3.exe and Rabbitmq-server-3.6.9.exe

Install Otp_win64_18.3.exe by default, and when finished, configure environment variables

Erlang_home C:\Program files\erl7.3

Add to Path

%erlang_home%\bin;

Install Rabbitmq-server-3.6.9.exe by default, and when finished, configure environment variables

Rabbitmq_server C:\Program FILES\RABBITMQ server\rabbitmq_server-3.6.9

Add to Path

%rabbitmq_server%\sbin;

Enter the Sbin directory to open a console and install the Web management plug-in

C:\Program FILES\RABBITMQ Server\rabbitmq_server-3.6.9\sbin>rabbitmq-plugins.bat Enable Rabbitmq_management

Then restart the service so that the above configuration takes effect (note here to use the admin to open the cmd command line, the path has no effect),

C:\windows\system32>net Stop RABBITMQ && net start rabbitmq
RABBITMQ service is stopping.
The RABBITMQ service has stopped successfully. The

RABBITMQ service is starting.
The RABBITMQ service has started successfully.


c:\windows\system32>

Open the browser, enter http://localhost:15672/, you can access the normal. Since I was installed on this machine, so here is localhost.

Next, configure an account and give administrator privileges (make sure it's a boot state, of course),

C:\Program files\rabbitmq server\rabbitmq_server-3.6.9\sbin>rabbitmqctl.bat add_user pony 123456
User "Pony"

... C:\Program files\rabbitmq server\rabbitmq_server-3.6.9\sbin>rabbitmqctl.bat set_user_tags Pony Administrator
Setting tags for the user "pony" to [Administrator] ...

Log in with this account on the Web side to be successful. Java Invocation Example

My development environment is in the MYECLIPSE+WIN10,WINDOWS environment has been configured in accordance with the previous chapters RABBITMQ services. * * Then keep the startup state. **java you need to rely on a client to use RABBITMQ. Download Address

If you use MAVEN, you don't need to download, the configuration file plus the dependency description.

I've created two new projects here, rabbitmqdemo-p (for producers) and RABBITMQDEMO-C (for consumers), and the two projects run to represent two separate processes that communicate through Message Queuing. Producers are constantly sending messages to message queues, and consumers are constantly fetching messages from queues. In the project, import the previously downloaded client dependency package.

Source code from: rabbitmq-tutorials

Eclipse Engineering Source Download address

First producer's Code:

Private final static String queue_name = "Hello";

    public static void Main (string[] args) throws exception{
        //TODO auto-generated method stub

        ConnectionFactory Tory = new ConnectionFactory ();
        Factory.sethost ("localhost");//Because two processes on the same machine
        Connection Connection = null;
        Channel Channel = null;

        Connection = Factory.newconnection ();
        Channel = Connection.createchannel ();

        Channel.queuedeclare (Queue_name, False, False, false, NULL);
        String message = "Hello world!";
        Channel.basicpublish ("", queue_name, NULL, Message.getbytes ("UTF-8"));
        System.out.println ("[Producer] Sent '" + Message + "'");

        Channel.close ();
        Connection.close ();
    }

Relatively simple, involved in the API specific instructions can search their own learning. Run one at a time to post a message to the queue named Hello: "Hello World", and then the process ends.

Consumers are a little bit more complicated,

private final static String queue_name = "Hello";
        public static void Main (string[] args) throws exception{connectionfactory factory = new ConnectionFactory ();
        Factory.sethost ("localhost");
        Connection Connection = Factory.newconnection ();

        Channel Channel = Connection.createchannel ();
        Channel.queuedeclare (Queue_name, False, False, false, NULL); SYSTEM.OUT.PRINTLN ("[*] waiting for messages.

        To exit Press CTRL + C "); Consumer Consumer = new Defaultconsumer (channel) {@Override public void handledelivery (String consume Rtag, Envelope Envelope, AMQP. Basicproperties properties, byte[] throws IOException {String message = new String (Body,
            "UTF-8");
          System.out.println ("[Consumer] Received '" + Message + "'");
        }
        };

    Channel.basicconsume (Queue_name, true, consumer); }

The Channel.basicconsume method binds the consumer to Message Queuing, which is defined as follows:

The first parameter is the queue name of the consumer binding, the second parameter is the automatic confirmation flag, and if true, the acknowledgment message (ACK message) is automatically sent to the message queue after the consumer is accepted, and Message Queuing deletes the message from the message queue. The third parameter is the consumer object, which is used to process the received message.

The third parameter is actually a callback, and when the consumer receives the message, the Handledelivery method of the Consumer object is invoked. We rewrite this method here and print it after we receive the message.

Run the consumer first, as follows:

[*] Waiting for messages. To exit Press CTRL + C

Start waiting for the message.

Re-run producers, as follows:

[Producer] Sent ' Hello world! '

Once again, look at the consumer's console information and receive a message:

[*] Waiting for messages. To exit Press CTRL + C
 [Consumer] Received ' Hello world! '
Related Article

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.