一、消息队列:
1、订阅渠道:subscribe channel1
2、推送信息:publish channel1 “hello motor”
二、springdata:
1)编写监听器:
public class MyMessageListener implements MessageListener { public void onMessage(Message message, byte[] pattern) { //1.获取渠道名称 String channel = new String(pattern); System.out.println("渠道名称:"+channel); //2.获取消息 byte[] body = message.getBody(); String info = new String(body); System.out.println("发布的消息:"+info); } }
2)配置:
<!--配置监听器的实现类--> <bean id="messageListener" class="com.qf.listener.MyMessageListener"/> <!-- 配置消息监听容器 --> <bean id="messageListenerContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy"> <!-- redis连接工厂 --> <property name="connectionFactory" ref="connectionFactory"/> <!-- 配置监听配置 --> <property name="messageListeners"> <map> <!-- 配置监听器 --> <entry key-ref="messageListener"> <!-- 配置监听的渠道 --> <bean class="org.springframework.data.redis.listener.ChannelTopic"> <!-- --> <constructor-arg name="name" value="channel1"/> </bean> </entry> </map> </property> </bean>
3)测试:
@Test public void testMessage(){ redisTemplate.convertAndSend("channel1","hello motor"); }