当多个客户端同时尝试 read/write 一个项目时,Redis 是原子的吗?
Is Redis atomic when multiple clients attempt to read/write an item at the same time?
假设我有几个 AWS Lambda 函数构成了我的 API。其中一个函数从单个 Redis 节点上的特定键读取特定值。业务逻辑如下:
if the key exists:
serve the value of that key to the client
if the key does not exist:
get the most recent item from dynamoDB
insert that item as the value for that key, and set an expiration time
delete that item from dynamoDB, so that it only gets read into memory once
Serve the value of that key to the client
这个想法是每次客户端发出请求时,他们都会获得所需的值。如果key已经过期,那么lambda需要先从数据库中取出item,然后放回Redis。
但是如果 2 个客户端同时对 lambda 进行 API 调用会怎样?两个 lambda 进程是否会读取没有密钥,并且都将从数据库中获取一个项目?
我的目标是实现一个队列,其中某个项目仅在内存中存在 X 时间,一旦该项目过期,就应该从数据库中提取下一个项目,当它被提取时,也应该删掉,这样就不会再拉了
我正在尝试看看是否有一种方法可以做到这一点,而无需单独的 EC2 进程来跟踪时间。
redis+lambda+dynamoDB 是否适合我要实现的目标,或者是否有更好的方法?
Redis 服务器将自动执行命令(或事务或脚本)。但是涉及单独服务(例如 Redis 和 DynamoDB)的一系列操作将不是原子的。
一种方法是通过在您的业务逻辑周围添加某种锁来使它们成为原子。例如,这可以是 done with Redis。
但是,这是一个成本高昂且相当麻烦的解决方案,因此如果可能,最好将您的业务逻辑简单地设计为在面对并发操作时具有弹性。为此,您必须查看这些步骤并想象如果多个客户端同时 运行 会发生什么。
在你的例子中,我看到的缺陷是可以从 DynamoDB 读取和删除两个值,一个在 Redis 中覆盖另一个。这可以通过使用 Redis 的 SETNX
(SET if Not eXists) 命令来避免。像这样:
GET the key from Redis
If the value exists:
Serve the value to the client
If the value does not exist:
Get the most recent item from DynamoDB
Insert that item into Redis with SETNX
If the key already exists, go back to step 1
Set an expiration time with EXPIRE
Delete that item from DynamoDB
Serve the value to the client
假设我有几个 AWS Lambda 函数构成了我的 API。其中一个函数从单个 Redis 节点上的特定键读取特定值。业务逻辑如下:
if the key exists:
serve the value of that key to the client
if the key does not exist:
get the most recent item from dynamoDB
insert that item as the value for that key, and set an expiration time
delete that item from dynamoDB, so that it only gets read into memory once
Serve the value of that key to the client
这个想法是每次客户端发出请求时,他们都会获得所需的值。如果key已经过期,那么lambda需要先从数据库中取出item,然后放回Redis。
但是如果 2 个客户端同时对 lambda 进行 API 调用会怎样?两个 lambda 进程是否会读取没有密钥,并且都将从数据库中获取一个项目?
我的目标是实现一个队列,其中某个项目仅在内存中存在 X 时间,一旦该项目过期,就应该从数据库中提取下一个项目,当它被提取时,也应该删掉,这样就不会再拉了
我正在尝试看看是否有一种方法可以做到这一点,而无需单独的 EC2 进程来跟踪时间。
redis+lambda+dynamoDB 是否适合我要实现的目标,或者是否有更好的方法?
Redis 服务器将自动执行命令(或事务或脚本)。但是涉及单独服务(例如 Redis 和 DynamoDB)的一系列操作将不是原子的。
一种方法是通过在您的业务逻辑周围添加某种锁来使它们成为原子。例如,这可以是 done with Redis。
但是,这是一个成本高昂且相当麻烦的解决方案,因此如果可能,最好将您的业务逻辑简单地设计为在面对并发操作时具有弹性。为此,您必须查看这些步骤并想象如果多个客户端同时 运行 会发生什么。
在你的例子中,我看到的缺陷是可以从 DynamoDB 读取和删除两个值,一个在 Redis 中覆盖另一个。这可以通过使用 Redis 的 SETNX
(SET if Not eXists) 命令来避免。像这样:
GET the key from Redis
If the value exists:
Serve the value to the client
If the value does not exist:
Get the most recent item from DynamoDB
Insert that item into Redis with SETNX
If the key already exists, go back to step 1
Set an expiration time with EXPIRE
Delete that item from DynamoDB
Serve the value to the client