Direct mode is required for the middle key.
Import Org.springframework.amqp.core.BindingBuilder;
Import Org.springframework.amqp.core.DirectExchange;
Import Org.springframework.amqp.core.Queue;
Import Org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
Import Org.springframework.amqp.rabbit.core.RabbitAdmin;
Import Org.springframework.amqp.rabbit.core.RabbitTemplate; public class Direct {public static void main (string[] args) {cachingconnectionfactory CF = new Cachingconnec
Tionfactory ("IP");
Cf.setusername ("root");
Cf.setpassword ("");
Rabbitadmin admin = new rabbitadmin (CF);
Queue queue2 = new Queue ("Q2");
Admin.declarequeue (queue2);
Directexchange exchange= New Directexchange ("ZDC");
Admin.declareexchange (Exchange); Admin.declarebinding (Bindingbuilder.bind (queue2). to (Exchange). With ("XX");//declare XX as a routing key//encapsulated template Rabbittem
Plate template = new rabbittemplate (CF); Template.convertandsend ("Zdc", "xx", "Hello, WoRld! ");}}
After binding effect:
One benefit of using spring is to convert dependencies into configuration files.
Add a spring-rabbit pom to maven
<!--https://mvnrepository.com/artifact/org.springframework.amqp/spring-rabbit-->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactid>spring-rabbit</ artifactid>
<version>1.7.3.RELEASE</version>
</dependency>
Spring configuration file
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:rabbit=" Http://www.springframework.org/schema/rabbit "xsi:schemalocation=" http:// Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www . springframework.org/schema/rabbit Http://www.springframework.org/schema/rabbit/spring-rabbit-1.7.xsd "> < Rabbit:connection-factory id= "connectionfactory" host= "IP" username= "root" password= ""/> <rabbit:admin connection-factory= "ConnectionFactory"/> <!--spring Template declaration--> <rabbit:template exchange= "AmqpE Xchange "Id=" Amqptemplate "connection-factory=" ConnectionFactory "/> <rabbit:queue name=" Test_queue_ke Y "></rabbit:queue> <rabbit:queue name=" test2 "></rabbit:queue> <!--declaring direct Exchange Mode--&
Gt
<rabbit:direct-exchange name= "Amqpexchange" > <rabbit:bindings> <rabbit:binding queue= "Test_queue_key" key= "XX" ></rabbit:binding>< !--bound queue--> <rabbit:binding queue= "test2" key= ' test2 ' ></rabbit:binding> </rabbit:bind Ings> </rabbit:direct-exchange> </beans>
In that case, sending the code is easier.
Abstractapplicationcontext CTX = new Classpathxmlapplicationcontext ("Rabbit.xml");
Rabbittemplate template = Ctx.getbean (rabbittemplate.class);
Template.convertandsend ("xx", "Hello"); The first parameter is the routing key, and the second parameter is the message that is actually sent.
Thread.Sleep (1000);
Ctx.destroy ();