在推模式中使用可以两种实现:
除消息外,还提供了Channel这个对象,通过channel可以有更大的灵活性。
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 {
}
}
基本的消息的临时。普通的场景基本够用。
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MesListener implements MessageListener {
@Override
public void onMessage(Message message) {
}
}
此处以ChannelAwareMessageListener为样例:
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
<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>
<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>
容器启动类
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ListenerApplication {
public static void main(String[] args) {
//启动Spring容器
new ClassPathXmlApplicationContext("spring-rabbit.xml");
}
}
首先启动消费者。这样监听者就会处于监听状态。
再启动生产者,向队列中发送消息。
再观察消息者,便能看到消费者队列中已经收到了发送的消息。
收到的消息是:hello world
在推模式中消息的即时性比拉模式会好。