【问题标题】:How to use Windows Azure Table Storage Timestamp or Etag field如何使用 Windows Azure 表存储时间戳或 Etag 字段
【发布时间】:2012-09-13 20:02:29
【问题描述】:

我正在 Windows Azure 网站 (IISNode) 上开发 node.js 应用程序,并为 node.js 安装了 Azure SDK 模块,我的问题是如何在表存储中使用 etag 或时间戳字段。

是“我”做某事的问题吗,例如:

if (entities[0].Timestamp == newEntity.Timestamp)
    // commit this update because we are dealing with the latest copy of this entity
else
    // oops! one of the entities is newer than the other, better not save it

或者我是否需要监听 tableService.updateEntity( ... 返回的错误或其他什么?

任何帮助或建议表示赞赏

【问题讨论】:

    标签: windows node.js azure etag


    【解决方案1】:

    正如尼尔所说,好的做法是让表服务处理与并发相关的事情。

    当我们使用客户端库从表服务中获取实体时,库会将与实体关联的 ETag(存在于实体的服务响应中)存储在 EntityDescriptior 实例中(EntityDescriptor 是由上下文中每个实体实例的库)

    当您提交更新实体的请求时,sdk 会准备 HTTP 请求,主体为实体,序列化为 XML,请求的 ETag 头为 ETag 值,存储在该实体对应的实体描述符中。

    当表服务收到这个更新实体实例的请求时,它会检查请求中的 ETag 是否与表存储中当前与实体关联的 ETag 匹配(如果与存储在服务中的实体关联的 ETag 发生变化,则其他更新在收到您的更新请求之前发生),如果它不匹配服务返回前置条件失败/冲突错误,通过在 412 或 409 的响应中设置 Http 状态代码。

    bool done = true;
    while (!done)
    {
        Stat statistics = _context.Execute<Stat>(new Uri("https://management.core.windows.net/<subscription-id>/services/storageservices/StatEntity?RowKey=..&PartitionKey=..").FirstOrDefault();
    
        try
        {
            // TODO: Update the entity, e.g. statistics.ReadCount++
            _context.UpdateObject(statistics);
            _context.SaveChanges();
            // success
            break;
        }
        catch (DataServiceRequestException exception)
        {
            var response = exception.Response.FirstOrDefault();
            if (response != null && (response.StatusCode == 412 || response.StatusCode == 409))
            {
                // Concurrency Exception - Entity Updated in-between
                // by another thread, Fetch the latest _stat entity and repeat operation
            }
            else
            {
                // log it and come out of while loop
                break;
            }
        }
        catch (Exception)
        {
            // log it and come out of while loop
            break;
        }
    }
    

    【讨论】:

    • 感谢大家的回复,那么当我收到 412 或 409 错误时如何处理这种情况?重新获取记录并使用新数据再次更新?构建一个重试循环来不断获取记录并尝试提交更改直到它成功是明智的吗?
    • 是的,你是对的,你可以使用重试循环。刚刚用示例更新了答案
    【解决方案2】:

    ETag 用于更新期间的乐观并发。 ETag 在您检索实体时自动设置,并在您更新该查询实体时自动上传。如果实体同时已被另一个线程更新,则更新将失败。 updateEntity 方法有一个可选参数 checkEtag,可用于修改此行为,方法是允许您指定无论其他线程是否已更新记录,更新都应成功 - 从而覆盖乐观并发。

    Windows Azure 存储服务 REST API 是 Windows Azure 存储的权威接口,当您想了解服务的 API 功能时,htis 是您可以参考的文档。描述 ETag 的文档一般是here

    【讨论】:

      猜你喜欢
      • 2017-03-11
      • 2021-09-07
      • 2017-03-28
      • 2011-09-18
      • 2012-11-04
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      相关资源
      最近更新 更多