最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python使用redis實現(xiàn)消息隊列(異步)的實現(xiàn)完整例程

 更新時間:2023年01月18日 10:26:49   作者:brandon_l  
本文主要介紹了python使用redis實現(xiàn)消息隊列(異步)的實現(xiàn)完整例程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

最近在用fastapi框架開發(fā)web后端,由于近幾年python異步編程大火,fastapi憑借高性能也火了起來。本篇介紹了在異步環(huán)境下實現(xiàn)redis消息隊列的方法,代碼可以直接拷貝到fastapi中使用。

安裝相關庫

pip install aioredis

消息隊列實現(xiàn)及使用

我們使用redis的stream類型作為消息隊列的載體

首先我們創(chuàng)建一個目錄作為項目目錄:works/

創(chuàng)建配置文件

在項目根目錄下新建文件works/.env

在文件中寫入

export APP_ENV=development

export REDIS_URL="192.168.70.130/"
export REDIS_USER=
export REDIS_PASSWORD=
export REDIS_HOST="192.168.70.130"
export REDIS_PORT=6379

代碼實現(xiàn)

在項目目錄下創(chuàng)建py文件works/main.py

import os
from dotenv import load_dotenv
import aioredis
import asyncio

load_dotenv()

class Redis():
? ? def __init__(self):
? ? ? ? """initialize ?connection """
? ? ? ? self.REDIS_URL = os.environ['REDIS_URL']
? ? ? ? self.REDIS_PASSWORD = os.environ['REDIS_PASSWORD']
? ? ? ? self.REDIS_USER = os.environ['REDIS_USER']
? ? ? ? self.connection_url = f"redis://{self.REDIS_USER}:{self.REDIS_PASSWORD}@{self.REDIS_URL}"
? ? ? ? self.REDIS_HOST = os.environ['REDIS_HOST']
? ? ? ? self.REDIS_PORT = os.environ['REDIS_PORT']
? ? ? ??
? ? async def create_connection(self):
? ? ? ? self.connection = aioredis.from_url(
? ? ? ? ? ? self.connection_url, db=0)

? ? ? ? return self.connection


class Producer:
? ? def __init__(self, redis_client):
? ? ? ? self.redis_client = redis_client

? ? async def add_to_stream(self, ?data: dict, stream_channel):
? ? ? ? """將一條數(shù)據(jù)添加到隊列

? ? ? ? Args:
? ? ? ? ? ? data (dict): _description_
? ? ? ? ? ? stream_channel (_type_): _description_

? ? ? ? Returns:
? ? ? ? ? ? _type_: _description_
? ? ? ? """
? ? ? ? try:
? ? ? ? ? ? msg_id = await self.redis_client.xadd(name=stream_channel, id="*", fields=data)
? ? ? ? ? ? print(f"Message id {msg_id} added to {stream_channel} stream")
? ? ? ? ? ? return msg_id

? ? ? ? except Exception as e:
? ? ? ? ? ? raise Exception(f"Error sending msg to stream => {e}")

class StreamConsumer:
? ? def __init__(self, redis_client):
? ? ? ? self.redis_client = redis_client

? ? async def consume_stream(self, count: int, block: int, ?stream_channel):
? ? ? ? """讀取隊列中的消息,但是并不刪除

? ? ? ? Args:
? ? ? ? ? ? count (int): _description_
? ? ? ? ? ? block (int): _description_
? ? ? ? ? ? stream_channel (_type_): _description_

? ? ? ? Returns:
? ? ? ? ? ? _type_: _description_
? ? ? ? """
? ? ? ? response = await self.redis_client.xread(
? ? ? ? ? ? streams={stream_channel: ?'0-0'}, count=count, block=block)

? ? ? ? return response

? ? async def delete_message(self, stream_channel, message_id):
? ? ? ? """成功消費數(shù)據(jù)后,調(diào)用此函數(shù)刪除隊列數(shù)據(jù)

? ? ? ? Args:
? ? ? ? ? ? stream_channel (_type_): _description_
? ? ? ? ? ? message_id (_type_): _description_
? ? ? ? """
? ? ? ? await self.redis_client.xdel(stream_channel, message_id)


async def main():
? ? redis_conn = await Redis().create_connection()
? ? produce = Producer(redis_conn)
? ? consumer = StreamConsumer(redis_conn)
? ? # 添加一個消息到隊列中
? ? data = {'xiaoming4':123}
? ? await produce.add_to_stream(data=data,stream_channel='message_channel')
? ??
? ? # 從隊列中拿出最新的1條數(shù)據(jù)
? ? data = await consumer.consume_stream(1,block=0,stream_channel='message_channel')
? ? print(data)
? ??
? ? # 輪詢等待隊列中的新消息
? ? response = await consumer.consume_stream(stream_channel="message_channel", count=1, block=0)
? ? if response:
? ? ? ? for stream, messagees in response:
? ? ? ? ? ? print('stream:',stream)
? ? ? ? ? ? for message in messagees:
? ? ? ? ? ? ? ? print('message: ',message)
? ? ? ? ? ? ? ? message_id = message[0]
? ? ? ? ? ? ? ? print('message_id: ',message_id)
? ? ? ? ? ? ? ? message_content = message[1]
? ? ? ? ? ? ? ? print('message_content: ',message_content)
? ? ? ? ? ? ? ? print('注意里面的鍵、值都變成了byte類型,需要進行解碼:')
? ? ? ? ? ? ? ? message_content:dict
? ? ? ? ? ? ? ? print('message_content_decode: ',{k.decode('utf-8'):v.decode('utf-8') for k,v in message_content.items()})

? ? # 消費成功后刪除隊列中的消息
? ? await consumer.delete_message(
? ? ? ? stream_channel='message_channel',message_id=message_id
? ? ) ? ?

if __name__ == '__main__':
? ? asyncio.run(main())

非常簡單好用,啟動一下看看吧

到此這篇關于python使用redis實現(xiàn)消息隊列(異步)的實現(xiàn)完整例程的文章就介紹到這了,更多相關python redis消息隊列內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

芜湖县| 新巴尔虎左旗| 莆田市| 武平县| 武汉市| 临洮县| 五寨县| 禄劝| 太原市| 宁晋县| 临安市| 闽清县| 突泉县| 金昌市| 平南县| 诸暨市| 无极县| 岑溪市| 雷波县| 青浦区| 资兴市| 同德县| 双鸭山市| 策勒县| 新闻| 沙坪坝区| 饶河县| 抚顺县| 茌平县| 阳朔县| 饶阳县| 穆棱市| 牡丹江市| 利津县| 衡山县| 乌拉特后旗| 鄂伦春自治旗| 黄陵县| 南充市| 西平县| 新乡市|