Redis 消息订阅(MessageListener接口)
在Java中,使用Jedis客户端可以通过实现MessageListener
接口来订阅Redis的频道消息。以下是一个简单的例子:
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
public class RedisMessageSubscriber {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
JedisPubSub listener = new Listener();
// 订阅一个频道
jedis.subscribe(listener, "channel1");
}
static class Listener extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
System.out.println("Received Message: " + message + " on channel: " + channel);
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
System.out.println("Subscribed to channel: " + channel + ", Total subscribed channels: " + subscribedChannels);
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
System.out.println("Unsubscribed from channel: " + channel + ", Total subscribed channels: " + subscribedChannels);
}
}
}
在这个例子中,我们创建了一个Jedis
实例来连接Redis服务器,然后创建了一个继承自JedisPubSub
的Listener
类,并覆盖了onMessage
、onSubscribe
和onUnsubscribe
方法来处理不同的订阅事件。最后,我们使用subscribe
方法来订阅名为"channel1"的频道。
当有消息发布到"channel1"时,Listener
类中的onMessage
方法会被调用,并打印出接收到的消息和频道。同样,当订阅或取消订阅频道时,onSubscribe
和onUnsubscribe
方法会被调用,并打印出相关信息。
评论已关闭