示例环境
1 2 3
|
python 3.10 redis 6.2 python redis 4.1.0
|
本实例所有包
1 2 3
|
from redis import StrictRedis, ConnectionPool from pprint import pprint from concurrent.futures.process import ProcessPoolExecutor
|
Basic
Basic Client
1 2 3 4 5 6 7 8 9
|
rds = StrictRedis( host='127.0.0.1', port=3218, username='default', password='xxxxwadsad', decode_responses=True, db=1, )
|
Basic Client Based On URL
1 2 3
|
rds_url = 'redis://default:xxxxwadsad@127.0.0.1:3218/1' rds = StrictRedis.from_url(rds_url) pprint(rds.info())
|
Connection Pool
Connection Pool class
1 2 3 4 5 6 7 8 9 10 11
|
connection_pool = ConnectionPool( host='127.0.0.1', port=3218, username='default', password='xxxxwadsad', decode_responses=True, db=1, ) connection_pool_client = StrictRedis(connection_pool=connection_pool) pprint(connection_pool_client.info())
|
Connection Pool class Base on URL
1 2 3 4
|
rds_url = 'redis://default:xxxxwadsad@127.0.0.1:3218/1' connection_pool = ConnectionPool.from_url(rds_url) connection_pool_client = StrictRedis(connection_pool=connection_pool) pprint(connection_pool_client.info())
|
Pipeline
Batch process, Don’t forget to use pipeline.execute()
after the batch is finished
1 2
|
pipeline = rds.pipeline(transaction=True) pipeline = connection_pool_client.pipeline(transaction=True)
|
multiprocessing batch
1 2 3 4 5 6 7 8 9 10
|
def process_item():
def main(): with ProcessPoolExecutor(max_workers=6) as p:
for _ in range(100): p.submit(process_item)
|
tips: IO密集型用线程、协程,CPU密集型用进程