如何使用python在redis通道中异步发布消息?

k4ymrczo  于 2021-06-08  发布在  Redis
关注(0)|答案(1)|浏览(412)

在我现有的djangorestapi中,我想从python代码的侧面在redis通道中发布一条消息。我想异步地做这件事,也就是说,我想调用一个异步函数,它将向通道发送一条消息,同时我的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
    )
zd287kbt

zd287kbt1#

你不能等待连接和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')

相关问题