amazon-web-services - 当多个客户端尝试同时读/写一个项目时,Redis 是原子的吗?

标签 amazon-web-services redis aws-lambda amazon-dynamodb atomic

假设我有几个构成我的 API 的 AWS Lambda 函数。其中一个函数从单个 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 需要先从数据库中获取该项目并将其放回 Redis。

但是如果 2 个客户端同时对 lambda 进行 API 调用会怎样?两个 lambda 进程是否会读取没有 key ,并且都将从数据库中获取一个项目?

我的目标是实现一个队列,其中某个项目仅在内存中保留 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

关于amazon-web-services - 当多个客户端尝试同时读/写一个项目时,Redis 是原子的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079560/

相关文章:

amazon-web-services - 当我尝试在 aws 上访问 ssh 时运行 ssh-add 后,我得到 "Permission denied (publickey)"

django - 将 Django 部署到 AWS Fargate 时,如何将本地 ip 添加到 ALLOWED_HOSTS

amazon-web-services - 多区域 ec2 实例复制

apache-spark - 如何在 Spark Streaming for Lookups 中创建到数据源的连接

amazon-web-services - Boto3 使用现有资源创建堆栈

amazon-web-services - 使用 Amazon Alexa 和 DynamoDB 进行日常持久化

amazon-web-services - SQS消息接收乱序

redis - 如何对 Redis 哈希执行地理空间操作

java - 无法弄清楚如何使用 Spring 2.0+ 在 Jedis 中设置 SSL 连接

python - 无法将 cvxpy 安装到 AWS lambda 的 virtualenv 中