【问题标题】:Azure table storage: concurrent updates overwritting previous changesAzure 表存储:覆盖先前更改的并发更新
【发布时间】:2022-10-17 21:37:42
【问题描述】:

我有一个程序可以像这样更新 Azure 表存储表中的条目:

  • 从按 partitionKey 和 item Id 过滤的表中恢复条目
  • 对已恢复对象的某些属性进行了一些更改。
  • 将更改保存回 BD。

因为我读过 Azure 存储表使用乐观并发和 Etag 属性(例如根据this,或者这个stackoverflow 问题on what is stored in Etag) 为了管理它,我想出了以下代码:

var query = table.CreateQuery<DynamicTableEntity>()
                   .Where(d => d.PartitionKey == customItem.PartitionKey
                   && d.Properties[nameof(CustomItem.CustomItemId)].GuidValue == Guid.Parse(StringValueOfId)
                   )
                   .AsTableQuery();

            var tr = table.ExecuteQuery<DynamicTableEntity>(query);

            if (tr != null)
            {
                var entity = new DynamicTableEntity(customItem.PartitionKey, StringValueOfId);
                entity.Properties.Add("MyDate", dateValue);
                entity.Properties.Add("CustomProperty", new EntityProperty(JsonConvert.SerializeObject(customItem)));
                entity.ETag = tr.FirstOrDefault().ETag;
                TableOperation mergeOperation = TableOperation.Replace(entity);
                try
                {
                    TableResult result = await table.ExecuteAsync(mergeOperation);
                    
                }
                catch (Exception ex)
                {
                    throw new StorageException("Error saving data:" + ex.Message);
                }

            }

现在我仍然遇到并发问题。基本上我的“CustomProperty”有 一个序列化的属性,其中一些字段为空。看起来,A和B都尝试 同时设置“CustomProperty”的值。其中之一是覆盖 对方的变化。

然而,由于“entity.ETag”的设置,我预计这是不可能的。 我期待如果A和B同时读取BD,然后A更新, 由于 entity.ETag 的值不匹配,B 的更新将失败。

有人可以告诉我我做错了什么吗?我不明白如何正确避免这些 并发问题?

【问题讨论】:

    标签: azure azure-table-storage azure-tablequery


    【解决方案1】:

    我发现了问题所在。这里的这一行有错误的 etag:

    entity.ETag = tr.FirstOrDefault().ETag;
    

    那就是埃塔格当我从数据库中读取行以恢复要更新的项目时,但实际上我需要埃塔格当我阅读自定义项财产。

    否则,此行可能会覆盖我恢复后发生的任何更改自定义项,但在我执行查询之前var tr = table.ExecuteQuery(query);

    entity.Properties.Add("CustomProperty", new EntityProperty(JsonConvert.SerializeObject(customItem)));
                
    

    换句话说,这解决了我的问题:

    entity.ETag = customItem.ETag
    

    【讨论】:

      猜你喜欢
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2022-08-06
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多