簡體   English   中英

無法從 Redis 訂閱中獲取數據?

[英]Get data out of Redis Subscription not possible?

我正在嘗試通過在我的客戶端應用程序上使用訂閱從 redis 通道獲取數據。 為此,我將 python 與 asyncio 和 aioredis 結合使用。

我想使用我的訂閱來更新我的主應用程序的一個變量,當它在服務器上更改時,但我無法將從訂閱接收到的數據傳遞給我的主線程。

根據 aioredis 網站,我實現了我的訂閱:

sub = await aioredis.create_redis(
     'redis://localhost')

ch1 = await sub.subscribe('channel:1')
assert isinstance(ch1, aioredis.Channel)

async def async_reader(channel, globarVar):
    while await channel.wait_message():
        msg = await channel.get(encoding='utf-8')
        # ... process message ...
        globarVar = float(msg)
        print("message in {}: {}".format(channel.name, msg))

tsk1 = asyncio.ensure_future(async_reader(ch1, upToDateValue))

但是我無法更新全局變量,我猜 python 只將當前值作為參數傳遞(我希望這樣做,但想確定)。

是否有任何可行的選擇可以從訂閱中獲取數據? 或者傳遞對我可以使用的共享變量或隊列的引用?

你應該重新設計你的代碼,這樣你就不需要全局變量了。 您的所有處理都應在收到消息時進行。 但是要修改全局變量,您需要在函數中使用 global 關鍵字聲明它。 您不會傳遞全局變量 - 您只需使用它們。

子:

import aioredis
import asyncio
import json

gvar = 2

# Do everything you need here or call another function
# based on the message.  Don't use a global variable.
async def process_message(msg):
  global gvar
  gvar = msg

async def async_reader(channel):
  while await channel.wait_message():
    j = await channel.get(encoding='utf-8')
    msg = json.loads(j)
    if msg == "stop":
      break
    print(gvar)
    await process_message(msg)
    print(gvar)

async def run(loop):
  sub = await aioredis.create_redis('redis://localhost')
  res = await sub.subscribe('channel:1')
  ch1 = res[0]
  assert isinstance(ch1, aioredis.Channel)

  await async_reader(ch1)

  await sub.unsubscribe('channel:1')
  sub.close()

loop = asyncio.get_event_loop()
loop.run_until_complete( run(loop) )
loop.close()

出版商:

import asyncio
import aioredis

async def main():
    pub = await aioredis.create_redis('redis://localhost')

    res = await pub.publish_json('channel:1', ["Hello", "world"])
    await asyncio.sleep(1)
    res = await pub.publish_json('channel:1', "stop")

    pub.close()


if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM