rabbitmq Java Client
After introducing the basic concepts of RABBITMQ, we use Java code to simulate a set of producer and consumer models, Talk is cheap directly on the code. Using Java Client consolidation RABBITMQ requires importing the following dependencies in Pom.xml
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactid>amqp-client</ artifactid>
<version>5.0.0</version>
</dependency>
This series of blog source git address: https://github.com/RobertoHuang/RGP-RABBITMQ.git related Code
1. Create a Connection tool class
public class Channelutils {public static Channel getchannelinstance (String connectiondescription) {try {
ConnectionFactory connectionfactory = Getconnectionfactory ();
Connection Connection = connectionfactory.newconnection (connectiondescription);
return Connection.createchannel ();
catch (Exception e) {throw new RuntimeException ("Get channel Connection Failed"); }} private static ConnectionFactory getconnectionfactory () {connectionfactory connectionfactory = new C
Onnectionfactory ();
Configure connection Information Connectionfactory.sethost ("192.168.56.128");
Connectionfactory.setport (5672);
Connectionfactory.setvirtualhost ("/");
Connectionfactory.setusername ("Roberto");
Connectionfactory.setpassword ("Roberto");
Network exception Automatic connection recovery connectionfactory.setautomaticrecoveryenabled (TRUE);
Try to retry the connection once every 10 seconds connectionfactory.setnetworkrecoveryinterval (10000);
Set ConnectionFactory property Information map<string, object> connectionfactorypropertiesmap = new HashMap ();
Connectionfactorypropertiesmap.put ("Principal", "Robertohuang");
Connectionfactorypropertiesmap.put ("description", "RGP Order System V2.0");
Connectionfactorypropertiesmap.put ("EmailAddress", "RobertoHuang@foxmail.com");
Connectionfactory.setclientproperties (CONNECTIONFACTORYPROPERTIESMAP);
return connectionfactory; }
}
2. Create a message producer
public class MessageProducer {public
static void Main (string[] args) throws IOException, timeoutexception {
Chan Nel channel = channelutils.getchannelinstance ("RGP Order system message producer");
Declares the switch (switch name, switch type, persistence, whether it is automatically deleted, whether it is an internal switch, switch properties);
Channel.exchangedeclare ("Roberto.order", Builtinexchangetype.direct, True, False, False, new hashmap<> ());
Set message properties to post messages (switch name, Routing key, reliable message related properties, message attributes, message body);
Amqp. Basicproperties basicproperties = new AMQP. Basicproperties (). Builder (). DeliveryMode (2). ContentType ("UTF-8"). Build ();
Channel.basicpublish ("Roberto.order", "add", False, Basicproperties, "order Information". GetBytes ());
}
3. Create Message consumers
public class Messageconsumer {public static void main (string[] args) throws IOException, TimeoutException {C
Hannel channel = channelutils.getchannelinstance ("RGP Order system Message Consumer");
declares queues (queue names, whether persisted, exclusive, whether automatically deleted, queue attributes); Amqp.
Queue.declareok Declareok = Channel.queuedeclare ("Roberto.order.add", True, False, False, new hashmap<> ());
Declares the switch (switch name, switch type, persistence, whether it is automatically deleted, whether it is an internal switch, switch properties);
Channel.exchangedeclare ("Roberto.order", Builtinexchangetype.direct, True, False, False, new hashmap<> ());
Binding the queue to the switch (queue name, switch name, Routing key, binding attribute);
Channel.queuebind (Declareok.getqueue (), "Roberto.order", "Add", New hashmap<> ()); Consumer subscription messages listen for queues such as those declared (queue names, whether they are automatically answered (with information about subsequent briefings), consumer labels, consumers) Channel.basicconsume (Declareok.getqueue (), True, "RG P Order System add handles logical consumer ", New Defaultconsumer (channel) {@Override public void Handledelivery (String consu Mertag, Envelope Envelope, AMQP. BasicprOperties properties, byte[] body) throws IOException {System.out.println (Consumertag);
System.out.println (Envelope.tostring ());
System.out.println (Properties.tostring ());
SYSTEM.OUT.PRINTLN ("Message content:" + new String (body));
}
}); }
}
4. Start message consumer and message producer in turn, console print
RGP Order system Add processing logic consumer
Envelope (deliverytag=1, Redeliver=false, Exchange=roberto.order, Routingkey=add)
# Contentheader<basic> (Content-type=utf-8, Content-encoding=null, Headers=null, delivery-mode=2, Priority=null , Correlation-id=null, Reply-to=null, Expiration=null, Message-id=null, Timestamp=null, Type=null, User-id=null, App-id=null, Cluster-id=null)
message content: Order information
Note: Be sure to run the producer after the first run, because there is no binding relationship between the queue and the switch at the first run, and if you start the producer first, the message will not be routed properly and discarded Console Configuration
After running the appeal code, open the RABBITMQ Admin console interface and see the configuration as follows
Connection Property Configuration:
Switch Property configuration:
Queue Property Configuration:
Combining management control console with appeal code will help readers understand the actual meaning of each line of code