如何解决Azure 函数和 Azure 存储 - 实体已存在 - nodeJS
我知道在 azure 存储表中插入实体的不同方法,但我找不到解决方案:
虽然我的函数是由队列触发的,但看起来有时尝试插入的实体已经存在于我的表中。
RowKey 是使用两个具有 4 位数字的数学随机数生成的,我知道这可能并不理想,因为相同的数字可以多次出现,但是您如何管理这种执行?
我使用输出绑定将数据发送到表,虽然在终止函数进程之前这个绑定应该尝试 5 次,但我只得到了 1 次尝试。 (我需要检查任何配置吗?)
是否可以在发生错误时捕获并在重新提交之前将 rowkey 增加 1 或更多?如果是的话,你有什么例子可以让我效仿吗?
这是通过输出绑定还是 JS sdk 完成的并不重要。
编辑: 我做了一些测试: 这有点奏效,但合法吗?
var azure = require('azure-storage');
var tableSvc = azure.createTableService(process.env.AzureWebJobsstorage);
module.exports = async function (context,myQueueItem) {
context.log('JavaScript queue trigger function processed work item',myQueueItem);
var partkey = "Test"
var rokey = 39
try {
context.bindings.outputTable = [];
context.bindings.outputTable.push({
PartitionKey: partkey,RowKey: rokey,Name: "Test"
});
} finally {
context.bindings.outputTable = [];
context.bindings.outputTable.push({
PartitionKey: partkey,RowKey: rokey + 1,Name: "Test"
});
}
}
现在存在 40 个,如果我再次运行,它会再次在 finally 上停止,因为在解决之前不会循环。
我是否应该在输入新实体之前查询表(具有大量条目)以检查密钥是否存在?这不会花很长时间吗?
非常感谢您的帮助
编辑1: 我一直在读到我无法真正捕获执行时的输出绑定错误,所以我尝试使用 tableservice (node js sdk)
var azure = require('azure-storage');
var tableSvc = azure.createTableService(process.env.AzureWebJobsstorage);
module.exports = async function (context,myQueueItem);
var partkey = "Test"
var rokey = "39"
var a = {
PartitionKey: partkey,Name: "ZuzzuS!"
};
tableSvc.insertEntity('TestTable',a,function(error,result,response) {
if(error) {
// Insert table entity error
context.log.error("There was an error!")
} else {
// Insert table entity successfully
}
});
}
这应该会报错,因为实体存在,而不是函数继续执行并完成而不做任何事情。
解决方法
关于这个问题,您可以使用insertOrMergeEntity
方法。如果实体不存在,该方法将插入实体。否则,该方法将通过将新属性值合并到实体中来更新表中的实体。详情请参阅here。
另外,如果你只是想做插入操作,请参考下面的代码
var azure = require("azure-storage");
var accountName = "andyprivate";
var accountKey =
"h4pP1fe76m8hdksFW3TvkO6hgw09Mjue7yJOnULPI/g2eU8LGJ+a6k6SrU6dUkOU77waZfU8CacyVMlTWAUA5A==";
var tableSvc = azure.createTableService(accountName,accountKey);
var entGen = azure.TableUtilities.entityGenerator;
module.exports = async function (context,myQueueItem) {
context.log(
"JavaScript queue trigger function processed work item",myQueueItem
);
var partkey = "Test";
var rokey = 29;
var task = {
PartitionKey: entGen.String(partkey),RowKey: entGen.String(String(rokey)),description: entGen.String("take out the trash"),};
try {
const r = await insert("test",task);
} catch (error) {
if (error.code == "EntityAlreadyExists") {
context.log(error);
// insert
}
}
};
async function insert(tableName,entity) {
return new Promise((resolve,reject) => {
tableSvc.insertEntity(tableName,entity,(error,result) => {
if (error) {
reject(error);
} else {
resolve("OK");
}
});
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。