asyncio实战案例
# 异步 redis
在使用 python 代码操作 redis 时,链接/操作/断开都是网络 IO
需要安装一个模块
pip3 install aioredis
1
示例 1:
import aioredis
import asyncio
async def execute(address, password):
print("开始执行", address)
# 网络IO操作,创建redis链接
redis = await aioredis.create_redis(address, password=password)
# 网络IO操作,在redis里设置哈希值car,内部设置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", ""))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
示例 2
import aioredis
import asyncio
async def execute(address, password):
print("开始执行", address)
# 网络IO操作,创建redis链接
redis = await aioredis.create_redis(address, password=password)
# 网络IO操作,在redis里设置哈希值car,内部设置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)
task_list = [
execute("redis://127.0.0.1:6379", ""),
execute("redis://127.0.0.1:6379", "")
]
asyncio.run(asyncio.await(task_list))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 异步 MySQL
安装一个模块
pip3 install aiomysql
1
示例 1:
import asyncio
import aiomysql
async def execute():
# 网络IO操作,连接mysql
conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='', db='mysql', )
# 网络IO操作,创建游标
cur = await conn.cursor()
# 执行sql
await cur.execute("select user,host from user")
# 网络IO操作,获取SQL执行结果
result = await cur.fetchall()
print(result)
# 网络IO操作,关闭连接
await cur.close()
conn.close()
asyncio.run(execute())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
上次更新: 2021/11/06, 16:07:33