如何在Redis通道中与python异步发布消息



在我现有的djangorest api中,我想在Redis通道中从python代码发布一条消息。我想异步完成,也就是说,我想调用一个异步函数,该函数将向通道发送一条消息,同时我的api应该响应用户,而不是在redis通信时阻塞。

让我们看看示例。

以下代码运行良好

#Python function (api function)
def create(self, request, *args, **kwargs):
queryset = Order.objects.all()
serializer_class = OrderSerializer
#some business logic
connection = redis.Redis(host=config("REDIS_SERVER_URL"), port=config("REDIS_SERVER_PORT"), db=config("REDIS_SERVER_DB"))
connection.publish('my_channel', 'my pubsub message')

return Response(      
data={
'status': True,
'message': "Order Successfully Created",
'data': response
},
status=status.HTTP_201_CREATED
)

但我不想等待redis连接和发布消息,而是想像下面这样异步进行


async def publish_message(channel, message):
connection = await redis.Redis(host=config("REDIS_SERVER_URL"), port=config("REDIS_SERVER_PORT"), db=config("REDIS_SERVER_DB"))
await connection.publish('channel', 'my pubsub message')
return "Nice"

#Python function (api function)
def create(self, request, *args, **kwargs):
queryset = Order.objects.all()
serializer_class = OrderSerializer
#some business logic
publish_message('my_channel', 'my pubsub message')

return Response(      
data={
'status': True,
'message': "Order Successfully Created",
'data': response
},
status=status.HTTP_201_CREATED
)

您不能等待连接和redis,因为它们不是corutines。它看起来像:

async def publish_message(channel, message):
connection = redis.Redis(host=config("REDIS_SERVER_URL"), port=config("REDIS_SERVER_PORT"), db=config("REDIS_SERVER_DB"))
connection.publish('channel', 'my pubsub message')
return "Nice"
def it_works():
await publish_message('gg', 'wp')

相关内容

最新更新