RABBITMQ Exchange Mode
Using spring to consolidate the AMQP protocol
The Fanout mode sends a message to multiple queues at the same time.
Use Spring-rabbit to wrap, add pom to maven configuration.
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId> spring-rabbit</artifactid>
<version>1.7.3.RELEASE</version>
</dependency>
Core code
Import Org.springframework.amqp.core.BindingBuilder;
Import Org.springframework.amqp.core.FanoutExchange;
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 Fanout {public static void main (string[] args) {cachingconnectionfactory CF = new Cachingconnec
Tionfactory ("IP");
Cf.setusername ("root");
Cf.setpassword ("");
Rabbitadmin admin = new rabbitadmin (CF);
Queue queue = new Queue ("Q1"),//Queue queue2 = new Queue ("Q2");
Admin.declarequeue (queue);
Admin.declarequeue (queue2);
Fanoutexchange Exchange = new Fanoutexchange ("Zdcex");
Admin.declareexchange (Exchange);
Admin.declarebinding (Bindingbuilder.bind (queue). to (Exchange);//Bind the queue to the switch. Admin.declarebinding (Bindingbuilder.bind (queue2). to (ExchaNGE)//Bind the queue to the switch//package rabbit template rabbittemplate template = new rabbittemplate (CF);
Template.convertandsend ("Zdcex", "Foo.bar", "Hello, world!"); }
}
The effect after binding:
Using the spring configuration file configuration:
<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--> <rabbit : Template exchange= "Amqpexchange" id= "Amqptemplate" connection-factory= "ConnectionFactory"/> <!--queue Declaration --> <rabbit:queue name= "Test_queue_key" ></rabbit:queue> <rabbit:queue name= "Test2" ></rabb It:queue> <!--exchange Statement--> <rabbit:fanout-exchange name= "Amqpexchange" > <rabbit:bindings> <rabbit:binding queue= "Test_queue_key" &G t;</rabbit:binding> <rabbit:binding queue= "test2" ></rabbit:binding> </rabbit:bind Ings> </rabbit:fanout-exchange> </beans>
Send code
public static void Main (string[] args) throws interruptedexception {
Abstractapplicationcontext ctx = new CLASSPATHXM Lapplicationcontext ("Rabbit.xml");
Rabbittemplate template = Ctx.getbean (rabbittemplate.class);
Template.convertandsend ("Hello");
Thread.Sleep (1000);
Ctx.destroy ();
}