根据 Redis 文档,Redis 是单线程的。但是我遇到了通过不同方法获取数据的奇怪情况。 我的redis存储4个散列,每个散列有50,000个键,每个值300xfloat32大小。 我尝试以三种方式获取数据,但得到了不同的计时结果。 1.串口方式: def fetch_data(): 对于范围 (4) 内的 i: r.hgetall(hash[i])
使用hgetall以串行方式获取数据,我在~4秒内获取数据
将 async wait 与 aioredis 结合使用,并收集,我得到了相同的计时,这是有道理的,因为瓶颈是 redis,而 redis 一次处理 1 个请求。
现在事情开始变得奇怪了,我使用多处理 python 库并且生成了 4 个进程,每个进程使用不同的哈希调用 r.hgetall(hash[i]) 并且我得到了整个数据1.5秒内
我的问题是,这与异步有何不同?在客户端使用线程如何提高获取时间? 请注意,我在主从架构中使用 AWS redis 弹性缓存。
这是我的案例 2 和案例 3 的代码: 情况2:
async def get_data_v7(intents_group):
try:
responses = list()
buckets = [bucket_1, bucket_2, bucket_3, bucket_4]
for i in range(len(buckets)):
responses.append(r.hgetall(buckets[i]))
await asyncio.gather(*responses)
except Exception as e:
print(f"Failed to get data from redis {e}")
案例3:
def fetch_data_from_redis(bucket_key):
bucket = r.hgetall(bucket_key)
try:
process_num = 4
processes = []
buckets = [bucket_1, bucket_2, bucket_3, bucket_4]
for i in range(process_num):
p = mp.Process(target=fetch_data_from_redis,
args=(buckets[i]))
processes.append(p)
p.start()
for p in processes:
p.join()
except Exception as e:
print(f"Failed to get data from redis {e}")
最佳答案
异步和线程术语不同,使用异步,您不必等待接收请求,但是,所有请求将仅由一个队列和一个线程处理
Elastic Cache 与开源 Redis 不同,因为它是多线程的
Availability – Unlike open-source Redis, ElastiCache cluster resizing is designed to run multi-threaded operations at the source shard, allowing slot migration to run on a separate thread from the main I/O thread. This allows ElastiCache to deliver a fully online experience and enables the cluster to serve incoming I/O requests while resizing is in progress.
关于python - 从 Redis 获取数据(异步、串行版本与多处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59519731/