要在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
實例,然后啟動監聽進程。
你可以根據實際情況修改代碼,使其適應你的需求。