Java Core Code
Import Org.springframework.amqp.core.BindingBuilder;
Import Org.springframework.amqp.core.Queue;
Import Org.springframework.amqp.core.TopicExchange;
Import Org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
Import Org.springframework.amqp.rabbit.core.RabbitAdmin;
Import Org.springframework.amqp.rabbit.core.RabbitTemplate; public class Topic {public static void main (string[] args) throws Interruptedexception {CACHINGCONNECTIONFAC
Tory CF = new cachingconnectionfactory ("IP");
Cf.setusername ("root");
Cf.setpassword ("");
Rabbitadmin admin = new rabbitadmin (CF);
Queue queue = new Queue ("Myqueue");
Admin.declarequeue (queue);
Topicexchange Exchange = new Topicexchange ("Myexchange");
Admin.declareexchange (Exchange);
Admin.declarebinding (Bindingbuilder.bind (queue). to (Exchange). With ("foo.*"));
Rabbittemplate template = new rabbittemplate (CF); Template.convertandsend ("Myexchange", "foO.bar "," Hello, world! ");
}
}
After binding, the effect is as follows:
Using the Spring configuration
Using Spring-rabbit
In topic mode, you need to specify the filtering mode
<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 "> <! --Connection Configuration--> <rabbit:connection-factory id= "connectionfactory" host= "IP" username= "root" password= ""/>
; <rabbit:admin connection-factory= "ConnectionFactory"/> <!--Spring Rabbit template declaration-->: Template exchange= "xxx" id= "amqptemplate" connection-factory= "ConnectionFactory"/> <rabbit:queue name = "Test_queue_key" ></rabbit:queue> <rabbit:queue name= "test2" ></rabbit:queue> <!--Exchange Statement--&
Gt <rabbit:topic-exchange name= "xxx" >;rabbit:bindings> <rabbit:binding queue= "Test_queue_key" pattern= "foo.*" ></rabbit:binding> </rabbit:bindings> </rabbit:topic-exchange> <beans>
Code:
Abstractapplicationcontext CTX = new Classpathxmlapplicationcontext ("Rabbit.xml");
Rabbittemplate template = Ctx.getbean (rabbittemplate.class);
Template.convertandsend ("Foo.df", "Hello");
Thread.Sleep (1000);
Ctx.destroy ();