Java使用RabbitMQ之整合Spring(生产者)

时间:2022-09-01 14:19:10

依赖包

        <!--RabbitMQ集成spring-->
<!-- https://mvnrepository.com/artifact/org.springframework.amqp/spring-rabbit -->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>

生产者Spring配置文件:

 <?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:context="http://www.springframework.org/schema/context"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd"> <!-- 连接服务配置 -->
<rabbit:connection-factory id="connectionFactory"
host="10.15.1.26" username="admin" password="admin" port="5672"
virtual-host="/test_host" channel-cache-size="5"/> <!--MQ的管理,包括队列、交换器的声明等-->
<rabbit:admin connection-factory="connectionFactory"/> <!-- queue 队列声明 -->
<rabbit:queue durable="true"
auto-delete="false" exclusive="false" name="test.spring.queue"/> <!-- exchange queue binging key 绑定 -->
<rabbit:direct-exchange name="spring.exchange"
durable="true" auto-delete="false">
<rabbit:bindings>
<rabbit:binding queue="test.spring.queue" key="spring.queue.key"/>
</rabbit:bindings>
</rabbit:direct-exchange> <!-- spring template声明 -->
<rabbit:template id="amqpTemplate" exchange="spring.exchange" routing-key="spring.queue.key"
connection-factory="connectionFactory"/> </beans>

生产者源码:

 package org.study.spring5;

 import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* RabbitMQ与Spring整合
* 生产者
*/
public class SpringProducer { public static void main(String args[]) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/producer-spring-config.xml");
//获取RabbitMQ模板
AmqpTemplate template = applicationContext.getBean(AmqpTemplate.class);
//发送消息
String msg = "Hello !";
template.convertAndSend(msg);
System.out.println("发送:" + msg);
}
}