推模式的消费者
在推模式中使用可以两种实现:
- 使用ChannelAwareMessageListener.
除消息外,还提供了Channel这个对象,通过channel可以有更大的灵活性。
java
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
public class MesListener implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
}
}
- 使用MessageListener
基本的消息的临时。普通的场景基本够用。
java
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MesListener implements MessageListener {
@Override
public void onMessage(Message message) {
}
}
此处以ChannelAwareMessageListener为样例:
java
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
public class MesListener implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
String encoding = message.getMessageProperties().getContentEncoding();
System.out.println("收到的消息是:" + new String(message.getBody(), encoding));
}
}
spring-rabbit.xml
xml
<?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: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/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
<!--配制连接工厂-->
<rabbit:connection-factory id="connectFactory"
host="node1" virtual-host="/"
username="root" password="123456"
port="5672"
></rabbit:connection-factory>
<!--用于自动向RabbitMQ声明队列、交换器、绑定 等操作工具类-->
<rabbit:admin id="rabbitAdmin" connection-factory="connectFactory"></rabbit:admin>
<!--用于简化操作的模板类-->
<rabbit:template connection-factory="connectFactory" id="rabbitTemplate"/>
<!--声明队列队列-->
<rabbit:queue id="msg1" name="queue.msg" durable="false" exclusive="false" auto-delete="false"></rabbit:queue>
<!--配制鉴别器对象-->
<bean id="msgListener" class="com.nullnull.learn.MesListener"/>
<!--配制监听器-->
<rabbit:listener-container connection-factory="connectFactory">
<rabbit:listener ref="msgListener" queues="msg1"></rabbit:listener>
</rabbit:listener-container>
</beans>
容器启动类
java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ListenerApplication {
public static void main(String[] args) {
//启动Spring容器
new ClassPathXmlApplicationContext("spring-rabbit.xml");
}
}
首先启动消费者。这样监听者就会处于监听状态。
再启动生产者,向队列中发送消息。
再观察消息者,便能看到消费者队列中已经收到了发送的消息。
java
收到的消息是:hello world
在推模式中消息的即时性比拉模式会好。