要在Java中监听Redis队列,你可以使用Redis的Pub/Sub(发布/订阅)功能。以下是一个示例代码:
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
public class RedisQueueListener extends Thread {
private Jedis jedis;
private String channel;
private JedisPubSub jedisPubSub;
public RedisQueueListener(Jedis jedis, String channel) {
this.jedis = jedis;
this.channel = channel;
this.jedisPubSub = new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
// 处理接收到的消息
System.out.println("Received message: " + message);
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
System.out.println("Subscribed to channel: " + channel);
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
System.out.println("Unsubscribed from channel: " + channel);
}
};
}
@Override
public void run() {
try {
jedis.subscribe(jedisPubSub, channel);
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
RedisQueueListener listener = new RedisQueueListener(jedis, "myQueue");
listener.start();
}
}
在上面的示例中,RedisQueueListener
类继承了Thread
类,以便可以在后台运行监听进程。在run()
方法中,使用jedis.subscribe()
方法订阅指定的频道,并通过JedisPubSub
类的回调方法处理接收到的消息。在main()
方法中,创建一个Jedis
实例,并创建一个RedisQueueListener
实例,然后启动监听进程。
你可以根据实际情况修改代码,使其适应你的需求。