通过Python操作Redis时,连接/读取/写入/断开过程都属于网络IO。
支持异步操作Redis的模块:aioredis
import asyncio
import aioredis
async def execute(address, password):
print(f'开始执行。 {address}')
# 网络IO操作:创建redis连接
redis = await aioredis.create_redis(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中获取值
value = await redis.hgetall('car', encoding='utf-8')
print(value)
redis.close()
# 网络IO操作:关闭redis连接
await redis.wait_closed()
print(f'结束执行。 {address}')
asyncio.run(execute('redis://47.93.4.198:6379', 'root!12345'))
import asyncio
import aioredis
async def execute(address, password):
print(f'开始执行。 {address}')
redis = await aioredis.create_redis_pool(address, password=password)
await redis.hmset_dict('car', key1=1, key2=2, key3=3)
value = await redis.hgetall('car', encoding='utf-8')
print(value)
redis.close()
await redis.wait_closed()
print(f'结束执行。 {address}')
task_list = [
asyncio.run(execute('redis://47.93.4.197:6379', 'root!12345')),
asyncio.run(execute('redis://47.93.4.198:6379', 'root!12345')),
]
asyncio.run(asyncio.wait(task_list))
import asyncio
import aiomysql
async def execute():
# 网络IO操作:连接MySQL
conn = await aiomysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123',
db='db1'
)
# 网络IO操作:创建CURSOR
cur = await conn.cursor()
# 网络IO操作:执行SQL语句
await cur.execute('SELECT id, name from user')
# 网络IO操作:获取结果
result = await cur.fetchall()
print(result)
# 网络IO操作:关闭连接
await cur.close()
conn.close()
asyncio.run(execute())
import asyncio
import aiomysql
async def execute(host, password):
conn = await aiomysql.connect(
host=host,
port=3306,
user='root',
password=password,
db='db1'
)
cur = await conn.cursor()
await cur.execute('SELECT id, name from user')
result = await cur.fetchall()
print(result)
await cur.close()
conn.close()
task_list = [
execute('47.93.40.197', 'root!1234'),
execute('47.93.40.198', 'root!2345'),
]
asyncio.run(asyncio.wait(task_list))
import asyncio
import uvicorn
import aioredis
from aioredis import Redis
from fastapi import FastAPI
app = FastAPI()
# 创建Redis连接池
REDIS_POOL = aioredis.ConnectionsPool(
'redis://47.193.14.198:6379',
password='root1234',
minsize=1,
maxsize=10,
)
@app.get('/')
def index():
# 普通操作接口
return {'message': 'Hello world!'}
@app.get('/red')
async def red():
# 异步操作接口
print('获取请求。')
await asyncio.sleep(1)
# 从连接池中获取一个连接
conn = await REDIS_POOL.acquire()
redis = Redis(conn)
# 设置值
await redis.hmset_dict('car', key1=1, key2=2, key3=3)
# 读取值
result = await redis.hgetall('car', encoding='utf-8')
print(result)
# 将连接归还连接池
REDIS_POOL.release(conn)
return result
if __name__ == '__main__':
uvicorn.run('Luffy:app', host='127.0.0.1', port=5000, log_level='info')
# 参数'Luffy:app'
# 脚本名称:Luffy.py
# app指的是上面创建的FastAPI对象:app = FastAPI()
import asyncio
import aiohttp
async def fetch(session, url):
print(f'发送请求。{url}')
async with session.get(url, verify_ssl=False) as response:
text = await response.text()
print(f'获取结果,{url} {len(text)}')
async def main():
async with aiohttp.ClientSession() as session:
url_list = [
'https://www.baidu.com/',
'https://www.csdn.net/',
'http://www.googlen.org/',
]
task_list = [asyncio.create_task(fetch(session, each_url)) for each_url in url_list]
done, pending = await asyncio.wait(task_list)
print(done)
print(pending)
if __name__ == '__main__':
asyncio.run(main())