python异步aioredis


一、异步redis连接(aioredis)

1.代码

import asyncio
import aioredis

async def execute(address, password):
    print('开始执行', address)
    # 网络IO操作:创建redis连接
    redis = await aioredis.create_redis(address=address, password=password)

    # 网络IO操作:在redis中设置哈希值car,内部再设三个键值对,即:redis = { car: { key1:1, key2:2, key3:3 } }
    await redis.hmset_dict('car', key1=1, key2=2, key3=3)

    # 网络IO操作:去redis中获取值
    result = await redis.hgetall('car', encoding='utf-8')
    print(result)

    redis.close()
    # 网络IO操作:关闭redis连接
    await redis.wait_closed()

    print('结束', address)


asyncio.run(execute('redis://127.0.0.1:6379', 'redis'))

2.报错详情

开始执行 redis://127.0.0.1:6379
Traceback (most recent call last):
  File "E:/Python/Python爬虫/asyncio异步编程/11-异步redis.py", line 22, in <module>
    asyncio.run(execute('redis://127.0.0.1:6379', 'redis'))
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 608, in run_until_complete
    return future.result()
  File "E:/Python/Python爬虫/asyncio异步编程/11-异步redis.py", line 7, in execute
    redis = await aioredis.create_redis(address=address, password=password)
  File "C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\aioredis\commands\__init__.py", line 168, in create_redis
    conn = await create_connection(address, db=db,
  File "C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\aioredis\connection.py", line 117, in create_connection
    address = sock.getpeername()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\asyncio\trsock.py", line 85, in getpeername
    return self._sock.getpeername()
OSError: [WinError 10014] 系统检测到在一个调用中尝试使用指针参数时的无效指针地址。
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002069D33C8B0>
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 116, in __del__
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 108, in close
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 711, in call_soon
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 504, in _check_closed
RuntimeError: Event loop is closed

3.解决方案

将传入的第一个参数redis://127.0.0.1:6379替换为元组(‘localhost’, 6379)即可正常运行
在这里插入图片描述

总结

解决了aioredis的报错,但具体缘由还不清楚

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值