redis java 队列_Redis 队列 Java调用简单实现
簡述
在本博客中,我們將會創建一個reids的消息隊列,Redis可以被當成消息隊列使用。消息會被存放在一個key-value集合中。
redis消息生產者使用RPUSH命令將消息添加到隊列的尾部,而消息消費者可以使用BLPOP命令獲取列表開頭的消息,使用FIFO(先進先出)規則。
注意:本博客前置條件,熟悉redis并且知道如何啟動redis服務器
Redis 隊列實現需要的maven依賴
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.leftso.redis
message-queue
1.0.0-SNAPSHOT
REDDIS - ${project.artifactId}
http://leftso.com
redis.clients
jedis
2.7.2
Redis消息隊列生產者
我們先使用rpush()方法將消息發布到mq-key隊列中。這條消息將會添加到列表的最末端。
import redis.clients.jedis.Jedis;
public class MessageProducer {
public static void main(String... args) {
Jedis jedis = new Jedis("localhost");
jedis.rpush("mq-key", "first message");
jedis.rpush("mq-key", "second message");
jedis.rpush("mq-key", "third message");
}
}
Redis消息隊列消費者
我們可以使用lpop()或者blpop()方法來消費消息。下面我們將會使用阻塞的lpop 方法,就如方法名稱一樣,使用該方法線程會進入阻塞狀態直到下一個消息過來。我們可以設置一個等待消息的超時時間。下面設置的超時時間為0,表示永久等待沒有超時時間。
import redis.clients.jedis.Jedis;
import java.util.List;
public class MessageConsumer {
private static final int TIMEOUT = 0;
public static void main(String... args ) {
Jedis jedis = new Jedis("localhost");
while(true){
System.out.println("Waiting for a message in the queue");
List messages = jedis.blpop(TIMEOUT, "mq-key");
System.out.println("received message with key:" + messages.get(0) + " with value:" + messages.get(1));
}
}
}
啟動消息隊列消費者
$title(console)
Waiting for a message in the queue
啟動消息隊列生產者
$title(console)
Waiting for a message in the queue
received message with key:mq-key with value:first message
Waiting for a message in the queue
received message with key:mq-key with value:second message
Waiting for a message in the queue
received message with key:mq-key with value:third message
Waiting for a message in the queue
參考文檔:
總結
以上是生活随笔為你收集整理的redis java 队列_Redis 队列 Java调用简单实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三菱M80操作介绍_三菱数控系统#645
- 下一篇: AudioPlayer.js实现限制仅播