1导入对应的jar包
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2 MyConsumer.java
public class MyConsumer {
//具体执行业务的方法
public void listen(String foo){
System.out.println("消费者:"+foo);
}
}
3 SpringMain.java
public class SpringMain {
public static void main(String[] args) throws Exception{
ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
//RabbitMQ模板
RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
//发送消息
template.convertAndSend("Hello world!");
TimeUnit.SECONDS.sleep(1);
((ClassPathXmlApplicationContext) ctx).destroy();//容器销毁
}
}
4 context.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/rabbit
https://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--1.定义RabbitMQ的连接工厂-->
<rabbit:connection-factory id="connectionFactory"
host="127.0.0.1" port="5672" username="xuanxuanxuan" password="12345678"
virtual-host="/db1"/>
<!--2.定义队列,自动声明-->
<rabbit:queue name="myQueue" auto-declare="true" durable="true"/>
<!--3.定义交换器,自动声明-->
<rabbit:fanout-exchange name="fanoutExchange" auto-declare="true">
<rabbit:bindings>
<rabbit:binding queue="myQueue"></rabbit:binding>
</rabbit:bindings>
</rabbit:fanout-exchange>
<!--4.定义Rabbit模板,指定连接工厂以及定义exchange-->
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="fanoutExchange"/>
<!--MQ的管理,包括队列、交换器声明等-->
<rabbit:admin connection-factory="connectionFactory"/>
<!--消费者-->
<bean id="foo" class="spring集成rabbitmqclient.MyConsumer"/>
<!--5.队列监听-->
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener ref="foo" method="listen" queue-names="myQueue"/>
</rabbit:listener-container>
</beans>