RABBITMQ Simple Java example-producers and consumers

Source: Internet
Author: User
Tags rabbitmq

Add Maven dependencies:

Use the latest MAVEN coordinates for Rabbitmq-client:

<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client --><dependency>    <groupId>com.rabbitmq</groupId>    <artifactId>amqp-client</artifactId>    <version>5.3.0</version></dependency>
Add an Account

By default, the user name and password for access to the RABBITMQ service are "guest", which is restricted by default only through local networks (such as localhost), and remote network access is restricted, so you need to add another user before you can implement production and consumption messages. and set the appropriate access rights.

Add a new user named "Zifeiy" with the password "passwd":

C:\Users\zifeiy>rabbitmqctl add_user zifeiy passwdAdding user "zifeiy" ...

To set all permissions for Zifeiy users:

C:\Users\zifeiy>rabbitmqctl set_permissions -p / zifeiy ".*" ".*" ".*"Setting permissions for user "zifeiy" in vhost "/" ...

Set user Zifeiy as Administrator role:

C:\Users\zifeiy>rabbitmqctl set_user_tags zifeiy administratorSetting tags for user "zifeiy" to [administrator] ...

The world of computers is from "Hello world!" Start, here we also follow the Convention, first the producer sends a message "Hello world!" To RABBITMQ, and then consumed by consumers.
The following shows the code for the producer client, and then the code for the consumer client.

Producer Client Code
Package Com.zifeiy.springtest.rabbitmq;import Java.io.ioexception;import java.util.concurrent.TimeoutException; Import Com.rabbitmq.client.channel;import Com.rabbitmq.client.connection;import    Com.rabbitmq.client.connectionfactory;import Com.rabbitmq.client.messageproperties;public class RabbitProducer {    private static final String Exchange_name = "Exchange_demo";    private static final String Routing_key = "Routingkey_demo";    private static final String queue_name = "Queue_demo";    private static final String ip_address = "127.0.0.1";   private static final int PORT = 5672; RABBITMQ Server default port number is 5672 public static void Main (string[] args) throws IOException, TimeoutException {Conne        Ctionfactory factory = new ConnectionFactory ();        Factory.sethost (ip_address);        Factory.setport (PORT);        Factory.setusername ("Zifeiy");        Factory.setpassword ("passwd");    Connection Connection = Factory.newconnection (); Establish connection Channel channel = ConnecTion.createchannel (); Create a channel//create a type= "direct", persistent, non-auto-deleted exchanger Channel.exchangedeclare (Exchange_name, "direct", True, False, Nu        ll);        Creates a persistent, non-exclusive, non-auto-deleted queue Channel.queuedeclare (Queue_name, True, False, false, NULL);        Binds the exchanger and the queue via routing Channel.queuebind (queue_name, Exchange_name, Routing_key);        Send a persistent message: Hello world!        String message = "hello,world!";                     Channel.basicpublish (Exchange_name, Routing_key, Messageproperties.persistent_text_plain,        Message.getbytes ());        Close resource Channel.close ();    Connection.close (); }}

Run.

Consumer client Code
Package Com.zifeiy.springtest.rabbitmq;import Java.io.ioexception;import Java.util.concurrent.timeunit;import Java.util.concurrent.timeoutexception;import Com.rabbitmq.client.amqp;import Com.rabbitmq.client.Address;import Com.rabbitmq.client.channel;import Com.rabbitmq.client.connectionfactory;import Com.rabbitmq.client.Consumer; Import Com.rabbitmq.client.defaultconsumer;import Com.rabbitmq.client.envelope;import    Com.rabbitmq.client.connection;public class Rabbitconsumer {private static final String queue_name = "Queue_demo";    private static final String ip_address = "127.0.0.1";        private static final int PORT = 5672; public static void Main (string[] args) throws IOException, TimeoutException, interruptedexception {address[] Addre        SSEs = new address[] {new Address (IP_Address, PORT)};        ConnectionFactory factory = new ConnectionFactory ();        Factory.setusername ("Zifeiy");        Factory.setpassword ("passwd"); The connection here is with the producer's DEmo slightly different, pay attention to differentiate Connection Connection = factory.newconnection (addresses); Create Connection final Channel Channel = Connection.createchannel ();   Create channel Channel.basicqos (64); Sets the maximum number of messages that the client accepts without being ack Consumer Consumer = new Defaultconsumer (channel) {@Override Public V OID Handledelivery (String consumertag, Envelope Envelope, AMQP. Basicproperties properties, byte[] body) throws IOException {System.out.println ("recv message:" + new STR                ing (body));                try {TimeUnit.SECONDS.sleep (1);                } catch (Interruptedexception e) {e.printstacktrace ();            } channel.basicack (Envelope.getdeliverytag (), false);        }        };        Channel.basicconsume (queue_name, consumer);        After waiting for the callback function to complete, close the resource TimeUnit.SECONDS.sleep (5);        Channel.close ();    Connection.close (); }}

Run, the command line output is as follows:

recv message: hello,world!

RABBITMQ Simple Java example-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.