如何使用Redis 做队列操作

2025-03-23 16:10:59
推荐回答(2个)
回答(1):

  • redis设计用来做缓存的,但是由于它自身的某种特性使得它可以用来做消息队列,它有几个阻塞式的API可以使用,正是这些阻塞式的API让其有能力做消息队列;

  • 另外,做消息队列的其他特性例如FIFO(先入先出)也很容易实现,只需要一个list对象从头取数据,从尾部塞数据即可;

  • redis能做消息队列还得益于其list对象blpop brpop接口以及Pub/Sub(发布/订阅)的某些接口,它们都是阻塞版的,所以可以用来做消息队列。

回答(2):

入队列操作文件 list_push.php

$redis = getRedisInstance();//从Redis服务器拿到redis实例
$redis->connect('Redis服务器IP', 6379);
while (true) {
$redis->lPush('list1', 'A_'.date('Y-m-d H:i:s'));
sleep(rand()%3);
}
?>

执行# php list_push.php &

出队列操作 list_pop.php文件
$redis = getRedisInstance();//从Redis服务器拿到redis实例
$redis->pconnect('Redis服务器IP', 6379);
while(true) {
try {
var_export( $redis->blPop('list1', 10) );
} catch(Exception $e) {
//echo $e;
}

}

实现方法(Python)

1.入队列(write.py)

#!/usr/bin/env python

import time

from redis import Redis

redis = Redis(host='127.0.0.1', port=6379)

while True:

now = time.strftime("%Y/%m/%d %H:%M:%S")

redis.lpush('test_queue', now)

time.sleep(1)

2.出队列(read.py)

#!/usr/bin/env python

import sys

from redis import Redis

redis = Redis(host='127.0.0.1', port=6379)

while True:

res = redis.rpop('test_queue')

if res == None:

pass

else:

print str(res)