您的位置:首页 > 编程语言 > Java开发

RabbitMQ-Spring集成

2018-03-11 22:56 330 查看
1.添加pom依赖

<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.5.RELEASE</version>
</dependency>


2.spring-rabbitmq配置文件

<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.7.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> 
<!--  1.定义RabbitMQ的连接工厂 -->
<rabbit:connection-factory id="connectionFactory"
host="10.102.150.244" port="5672" username="hzk" password="hzk"
virtual-host="/vhost_hzk" />

<!-- 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" durable="true"/>

<!-- 定义交换器,自动声明 -->
<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="recv" method="listen" queue-names="myQueue" />
</rabbit:listener-container>

<!-- 消费者 -->
<bean id="recv" class="com.ithzk.rabbitmq.spring.MyConsumer" />

</beans>


3.生产者

package com.ithzk.rabbitmq.spring;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* @author hzk
* @date 2018/3/11
*/
public class ProduceMain {

public static void main(String[] args) throws InterruptedException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring-rabbitmq.xml");
//RabbitMQ模板
RabbitTemplate rabbitTemplate = ctx.getBean(RabbitTemplate.class);
//发送消息
rabbitTemplate.convertAndSend("hello spring rabbit");
Thread.sleep(1000);
//容器销毁
ctx.destroy();
}
}


4.消费者

package com.ithzk.rabbitmq.spring;

/**
* @author hzk
* @date 2018/3/11
*/
public class MyConsumer {

//具体执行业务的方法
public void listen(String msg){

System.out.println("recv " + msg);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  RabbitMQ Java Spring