相信你如果看过RabbitMq详细入门学习介绍一的5种消息队列模式是不是有点烦锁复杂。那么在这里,幸运的是,Spring提供了对rabbitMQ的封装,将复杂的关系设置整合到配置文件中。
依赖于两个组件,抽象层spring-amqp和实现层spring-rabbit。
于是代码简化为:
生产者:
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(); //容器销毁
}
}
消费者:
public class Foo {
//具体执行业务的方法
public void listen(String foo) {
System.out.println("消费者: " + foo);
}
}
spring-rabbitmq.xml的封装配置如下:
<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.1.xsd">
<!--1 定义RabbitMQ的连接工厂 -->
<rabbit:connection-factory id="connectionFactory"
host="127.0.0.1" port="5672" username="learn" password="learn"
virtual-host="/mystore" />
<!--2 定义Rabbit模板,指定连接工厂以及定义exchange -->
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="fanoutExchange" />
<!-- MQ的管理,包括队列、交换器等 -->
<rabbit:admin connection-factory="connectionFactory" />
<!-- 定义队列,自动声明 -->
<rabbit:queue name="myQueue" auto-declare="true"/>
<!-- 3 定义交换器,自动声明 -->
<rabbit:fanout-exchange name="fanoutExchange" auto-declare="true">
<rabbit:bindings>
<rabbit:binding queue="myQueue"/>
</rabbit:bindings>
</rabbit:fanout-exchange>
<!-- 消费队列监听 -->
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener ref="foo" method="listen" queue-names="myQueue" />
</rabbit:listener-container>
<!-- 消费者-->
<bean id="foo" class="com.learn.rabbitmq.spring.Foo" />
</beans>
spring-rabbitmq.xml配置的图解
源码下载地址:https://github.com/oneboat/spring-rabbitmq