日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

redis java 队列_Redis 队列 Java调用简单实现

發(fā)布時間:2024/3/24 java 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 redis java 队列_Redis 队列 Java调用简单实现 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

簡述

在本博客中,我們將會創(chuàng)建一個reids的消息隊列,Redis可以被當(dāng)成消息隊列使用。消息會被存放在一個key-value集合中。

redis消息生產(chǎn)者使用RPUSH命令將消息添加到隊列的尾部,而消息消費者可以使用BLPOP命令獲取列表開頭的消息,使用FIFO(先進先出)規(guī)則。

注意:本博客前置條件,熟悉redis并且知道如何啟動redis服務(wù)器

Redis 隊列實現(xiàn)需要的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消息隊列生產(chǎn)者

我們先使用rpush()方法將消息發(fā)布到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 方法,就如方法名稱一樣,使用該方法線程會進入阻塞狀態(tài)直到下一個消息過來。我們可以設(shè)置一個等待消息的超時時間。下面設(shè)置的超時時間為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

啟動消息隊列生產(chǎn)者

$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

參考文檔:

總結(jié)

以上是生活随笔為你收集整理的redis java 队列_Redis 队列 Java调用简单实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。