introduce pom content:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactid>amqp-client</ artifactid>
<version>3.3.4</version>
</dependency>
send-side code:
Package com;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
Import Com.rabbitmq.client.ConnectionFactory;
Import com.rabbitmq.client.MessageProperties;
public class Producer {private static String QueueName = "Queue2";
public static void Main (string[] args) throws exception{connectionfactory factory = new ConnectionFactory ();
Factory.sethost ("127.0.0.1");
Factory.setusername ("admin");
Factory.setpassword ("admin");
Connection Connection = Factory.newconnection ();
Channel Channel = Connection.createchannel ();
Channel.queuedeclare (QueueName, True, False, false, NULL); for (int i = 0; i < i++) {//messages sent String message = "Hello world!"
+i; Send a message to the queue Channel.basicpublish ("", QueueName, Messageproperties.persistent_text_plain, Message.getbytes ()
);
System.out.println ("[X] Sent '" + Message + "'");
Thread.Sleep (1000);//Close the channel and connect Channel.close ();
Connection.close ();
}
}
Receive-side code:
Package com;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
Import Com.rabbitmq.client.ConnectionFactory;
Import Com.rabbitmq.client.QueueingConsumer;
public class Consumer {private static String QueueName = "Queue2";
public static void Main (string[] args) throws Exception {ConnectionFactory factory = new ConnectionFactory ();
Factory.sethost ("127.0.0.1");
Factory.setusername ("admin");
Factory.setpassword ("admin");
Connection Connection = Factory.newconnection ();
Channel Channel = Connection.createchannel ();
Declares queues, primarily to prevent message recipients from running the program, and to create queues when they do not exist.
Channel.queuedeclare (QueueName, True, False, false, NULL); System.out.println (Consumer.class.hashCode () + "[*] waiting for messages."
To exit Press CTRL + C ");
Create queue consumer Queueingconsumer consumer = new Queueingconsumer (channel);
Set maximum service message receive quantity int prefetchcount = 1;
Channel.basicqos (Prefetchcount); Boolean ack = FALSE; Whether to automatically confirm the message was successfully consumed Channel.basicconsume (QueueName, aCK, consumer); Specify consumption queue while (true) {//Nextdelivery is a blocking method (internal implementation is actually a take method for blocking queues) queueingconsumer.delivery Delivery = Consumer
. Nextdelivery ();
String message = new String (Delivery.getbody ());
System.out.println ("[X] Received '" + Message + "'");
Channel.basicack (Delivery.getenvelope (). Getdeliverytag (), false);
Thread.Sleep (2000);
}
}
}