假设有这样一个需求,你需要从 Redis 中持续不断读取数据,并把这些数据写入到 MongoDB 中。你可能会这样写代码:
import json
import redis
import pymongo
client = redis.Redis()
handler = pymongo.MongoClient().example.col
while True:
data_raw = client.blpop('data', timeout=300)
if not data_raw:
continue
data = json.loads(data_raw[1].decode())
handler.insert_one(data)
但这样写有一个问题,就是每来一条数据都要连接一次 MongoDB,大量时间浪费在了网络 I/O上。
于是大家会把代码改成下面这样:
import json
import redis
import pymongo
client = redis.Redis()
handler = pymongo.MongoClient().example.col
to_be_insert = []
while True:
data_raw = client.blpop('data', timeout=300)
if not data_raw:
continue
data = json.loads(data_raw[1].decode())
to_be_i