1. 向springboot中注冊redis消息監(jiān)聽器容器和消息監(jiān)聽器適配器
package com.summer.config;
import com.summer.server.RedisReceiver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
@Configuration
class RedisListenerConfig {
/**
* redis消息監(jiān)聽器容器
* 可以添加多個監(jiān)聽不同話題的redis監(jiān)聽器,只需要把消息監(jiān)聽器和相應(yīng)的消息訂閱處理器綁定,該消息監(jiān)聽器
* 通過反射技術(shù)調(diào)用消息訂閱處理器的相關(guān)方法進行一些業(yè)務(wù)處理
* @param connectionFactory
* @param listenerAdapter
* @return
*/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
//可以添加多個 messageListener
container.addMessageListener(listenerAdapter, new PatternTopic("index"));
return container;
}
/**
* 消息監(jiān)聽器適配器袜茧,綁定消息處理器屿良,利用反射技術(shù)調(diào)用消息處理器的業(yè)務(wù)方法
* @param redisReceiver
* @return
*/
@Bean
MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) {
System.out.println("消息適配器進來了");
return new MessageListenerAdapter(redisReceiver, "receiveMessage");
}
}
2.編寫RedisReceiver類,并編寫receiveMessage
原理是listenerAdapter會通過反射機制將自己原有代碼的receiveMessage方法替換為我們自己編寫的receiveMessage方法惫周。只要有消息傳來就會自動調(diào)用receiveMessage方法并傳入message的參數(shù)尘惧。
package com.summer.server;
import org.springframework.stereotype.Service;
@Service
public class RedisReceiver {
public void receiveMessage(String message) {
System.out.println("消息來了:"+message);
}
}