Redis一大特色就是拥有多种数据类型,其中的LIST是有序列表,利用其特性可以很方便的模拟一个队列。
下面的代码示例展示了一个简单的Redis邮件发送队列:
def send_email_via_queue(conn, to_email, content): data = { 'to_email': to_email, 'subject': subject, 'content': content, 'time': time.time() } conn.rpush('queue:email', json.dumps(data)) def process_email_queue(conn): while not QUIT: packed = conn.blpop('queue:email', 30) if not packed: continue to_send = json.loads(packed[1]) try: send_email(to_send) # 发送邮件,具体实现就不在这体现了 except EmailSendError as err: log_error("Failed to send email", err, to_send) else: log_success("Sent sold email", to_send)
这里的“queue:email”就是一个邮件发送队列,send_email_via_queue方法将等待发送的邮件从右侧推入队列,而process_email_queue则从左侧取出并投递邮件。BLPOP是有阻塞的列表弹出,即当队列为空时,连接将被阻塞,直到30秒后超时。如果当前没有需要发送的邮件,则函数继续循环检测。
实打实的
大苏打