Spring+RabbitMq簡單例子

依賴

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

簡單配置

<?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:p="http://www.springframework.org/schema/p" 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.5.xsd">
    <rabbit:connection-factory id="connectionFactory"
        host=ip port="5672" username="" password="" />
    <!-- <property name="channelCacheSize" value="25"/> -->
    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
        reply-timeout="2000" />
    <rabbit:admin connection-factory="connectionFactory" />
</beans>

測試

ApplicationContext acc = new ClassPathXmlApplicationContext("applicationContext.xml");
AmqpTemplate template = acc.getBean(AmqpTemplate.class);
RabbitAdmin rabbitAdmin = acc.getBean(RabbitAdmin.class);
//創建exchange, queue及binding, 如果不存在的話
rabbitAdmin.declareExchange(new FanoutExchange(name));  //name爲要建立的queue名
rabbitAdmin.declareQueue(new Queue(name));
rabbitAdmin.declareBinding(new Binding(name, Binding.DestinationType.QUEUE, name, "", null));
//data要發往queue中的數據
template.convertAndSend(name, data);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章