项目地址
http://spring.io/projects
提供了对AMOP的支持
提供了RabbitMQ的实现
http://spring.io/projects/spring-amqp
配置文件
第一步,定义连接工厂
第二步,定义模板,可以指定交换机或队列
第三步,定义队列、交换机、以及完成队列和交换机的绑定
第四步,定义监听
第五步,定义管理,用于管理队列、交换机等
Durable
表示对持久化的配置
True,表示持久化
False,表示非持久化
<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
http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 定义RabbitMQ的连接工厂 -->
<rabbit:connection-factory id="connectionFactory"
host="127.0.0.1" port="5672" username="taotao" password="taotao"
virtual-host="/taotao" />
<!-- 定义Rabbit模板,指定连接工厂以及定义exchange -->
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
exchange="fanoutExchange" />
<!-- <rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
exchange="fanoutExchange" routing-key="foo.bar" /> -->
<!-- MQ的管理,包括队列、交换器等 -->
<rabbit:admin connection-factory="connectionFactory" />
<!-- 定义队列,自动声明 -->
<rabbit:queue name="myQueue" auto-declare="true" />
<!-- 定义交换器,自动声明 -->
<rabbit:fanout-exchange name="fanoutExchange"
auto-declare="true" durable="true">
<rabbit:bindings>
<rabbit:binding queue="myQueue" />
</rabbit:bindings>
</rabbit:fanout-exchange>
<!-- <rabbit:topic-exchange name="myExchange"> <rabbit:bindings> <rabbit:binding
queue="myQueue" pattern="foo.*" /> </rabbit:bindings> </rabbit:topic-exchange> -->
<!-- 队列监听 -->
<rabbit:listener-container
connection-factory="connectionFactory">
<rabbit:listener ref="foo" method="listen"
queue-names="myQueue" />
</rabbit:listener-container>
<bean id="foo" class="cn.itcast.rabbitmq.spring.Foo" />
</beans>
生产者
package cn.itcast.rabbitmq.spring;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringMain {
public static void main(final String... args) throws Exception {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:spring/rabbitmq-context.xml");
//RabbitMQ模板
RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
//发送消息
template.convertAndSend("Hello, world!");
Thread.sleep(1000);// 休眠1秒
ctx.destroy(); //容器销毁
}
}
消费者
package cn.itcast.rabbitmq.spring;
/**
* 消费者
* @author zhijun
*
*/
public class Foo {
//具体执行业务的方法
public void listen(String foo) {
System.out.println("消费者: " + foo);
}
}