我试图通过在我的客户端应用程序上使用订阅从redis通道获取数据。为此,我正在使用带有asyncio和aioredis的python。
我希望使用我的订阅在服务器上更改主应用程序的变量时更新,但我无法将从订阅接收的数据传递给我的主线程。
根据aioredis website,我实施了我的订阅:
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())