Spring Boot整合Redis实现发布/订阅功能
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.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
@Configuration
public class RedisSubscriberConfig {
@Bean
RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(messageListenerAdapter(), topic());
return container;
}
@Bean
MessageListenerAdapter messageListenerAdapter() {
return new MessageListenerAdapter(new RedisMessageSubscriber());
}
@Bean
String topic() {
return "myTopic";
}
}
class RedisMessageSubscriber {
// 实现消息处理逻辑
public void handleMessage(String message) {
System.out.println("Received Redis message: " + message);
}
}
这个代码实例展示了如何在Spring Boot应用中配置Redis消息监听器以订阅特定的通道。RedisMessageSubscriber
类中的handleMessage
方法将处理接收到的每条消息。这个例子简单明了,并且提供了一个清晰的模板,可以根据实际需求进行扩展和修改。
评论已关闭