rabbitmq通信方式为6种,这里只介绍直连交换机模式!!详情登录官网
maven配置:
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> <version>1.4.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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.3.xsd"> <context:property-placeholder location="classpath:rabbitmq.properties" /> <!--配置connection-factory,指定连接rabbit server参数--> <rabbit:connection-factory id="connectionFactory" host="${mq.host}" username="${mq.username}" password="${mq.password}" /> <!--通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成--> <rabbit:admin connection-factory="connectionFactory"/> <!--定义queue--> <rabbit:queue id="com.mq.test" name="com.mq.test" durable="true" auto-delete="false" exclusive="false"/> <!-- 定义直连 exchange,绑定com.mq.test queue --> <rabbit:direct-exchange name="directExchange" durable="true" auto-delete="false"> <rabbit:bindings> <rabbit:binding queue="com.mq.test" key="add"></rabbit:binding> </rabbit:bindings> </rabbit:direct-exchange> <!--定义rabbit template用于的发送--> <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="directExchange"
message-converter
="
jsonMessageConverter
"
/><!-- 定义接收队列 --> <bean id="messageReceiver" class="...........QueueListenter"></bean><!-- 定义json转换器 --><bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />
<rabbit:listener-container connection-factory="connectionFactory"> <rabbit:listener queues="com.mq.test" ref="messageReceiver"/> </rabbit:listener-container> </beans>
发送消息:(任意类)
@Autowired private AmqpTemplate amqpTemplate; @Test public void send() throws Exception{ amqpTemplate.convertAndSend("add", object); }接收消息(实现messagelistenner接口):
public class QueueListenter implements MessageListener { @Override public void onMessage(Message msg) { try{ System.out.println(new String(msg.getBody(),"UTF-8")); }catch(Exception e){ e.printStackTrace(); } } }