Java使用RabbitMQ之整合Spring(生產者)
阿新 • • 發佈:2018-09-14
獲取 消息 org str 依賴 chang import name 5.1
依賴包
<!--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.xsd11 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(生產者)