Java使用RabbitMQ之整合Spring(生产者)
Posted 星瑞的随笔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java使用RabbitMQ之整合Spring(生产者)相关的知识,希望对你有一定的参考价值。
依赖包
<!--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配置文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:rabbit="http://www.springframework.org/schema/rabbit" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/rabbit 12 http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd"> 13 14 <!-- 连接服务配置 --> 15 <rabbit:connection-factory id="connectionFactory" 16 host="10.15.1.26" username="admin" password="admin" port="5672" 17 virtual-host="/test_host" channel-cache-size="5"/> 18 19 <!--MQ的管理,包括队列、交换器的声明等--> 20 <rabbit:admin connection-factory="connectionFactory"/> 21 22 <!-- queue 队列声明 --> 23 <rabbit:queue durable="true" 24 auto-delete="false" exclusive="false" name="test.spring.queue"/> 25 26 <!-- exchange queue binging key 绑定 --> 27 <rabbit:direct-exchange name="spring.exchange" 28 durable="true" auto-delete="false"> 29 <rabbit:bindings> 30 <rabbit:binding queue="test.spring.queue" key="spring.queue.key"/> 31 </rabbit:bindings> 32 </rabbit:direct-exchange> 33 34 <!-- spring template声明 --> 35 <rabbit:template id="amqpTemplate" exchange="spring.exchange" routing-key="spring.queue.key" 36 connection-factory="connectionFactory"/> 37 38 </beans>
生产者源码:
1 package org.study.spring5; 2 3 import org.springframework.amqp.core.AmqpTemplate; 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 /** 8 * RabbitMQ与Spring整合 9 * 生产者 10 */ 11 public class SpringProducer { 12 13 public static void main(String args[]) { 14 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/producer-spring-config.xml"); 15 //获取RabbitMQ模板 16 AmqpTemplate template = applicationContext.getBean(AmqpTemplate.class); 17 //发送消息 18 String msg = "Hello !"; 19 template.convertAndSend(msg); 20 System.out.println("发送:" + msg); 21 } 22 }
以上是关于Java使用RabbitMQ之整合Spring(生产者)的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot 2.X - Spring Boot整合AMQP之RabbitMQ
SpringBoot整合RabbitMQ之Spring事件驱动模型
荧客技荐RabbitMQ 实战之 Spring Boot 整合 RabbitMQ