我正在尝试使用Azure Functions连接Azure DocumentDB并保存文档,但我不知道如何创建连接。
我正在尝试使用Azure Functions连接Azure DocumentDB并保存文档,但我不知道如何创建连接。
您可以使用Azure门户完成此操作。 在创建了DocumentDB之后 -
例如
using System;
public static void Run(string input, out object document, TraceWriter log)
{
log.Info($"C# manually triggered function called with input: {input}");
document = new {
text = $"I'm running in a C# function! {input}"
};
}
CosmosDBTrigger
绑定属性进行输入绑定,例如(以C#为例):public static class UpsertProductCosmosDbTrigger
{
[FunctionName("ProductUpsertCosmosDbTrigger")]
public static void Run(
[CosmosDBTrigger(
// Those names come from the application settings.
// Those names can come with both preceding % and trailing %.
databaseName: "CosmosDbDdatabaseName",
collectionName: "CosmosDbCollectionName",
LeaseDatabaseName = "CosmosDbDdatabaseName",
LeaseCollectionName = "CosmosDbLeaseCollectionName")]
IReadOnlyList<Document> input,
TraceWriter log)
...
对于输出绑定,请在 V1 中使用 DocumentDB
输出绑定属性,在 V2 中使用 CosmosDB
,如下所示:
[FunctionName("ProductUpsertHttpTrigger")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "products")]
HttpRequestMessage req,
[DocumentDB(
databaseName: "%CosmosDbDdatabaseName%",
collectionName: "%CosmosDbCollectionName%")] IAsyncCollector<Product> collector,
TraceWriter log)
...
var endpoint = "https://XXXXX.documents.azure.com:443/";
var authKey = "XXXXX";
using (var client = new DocumentClient(new Uri(endpoint), authKey))
{
var sqlCountQuery = "select value count(1) from c";
IDocumentQuery<dynamic> query = client.CreateDocumentQuery<dynamic>(UriFactory.CreateDocumentCollectionUri("YOUR_DB_ID", "YOUR_COLLECTON_ID"), sqlCountQuery).AsDocumentQuery();
....
}
var EndpointUrl = "EndpointUrl";
var PrimaryKey = "PrimaryKeyValue"
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
Database database = await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = cosmoDbName });
您可以在 Azure 门户的密钥部分获取终结点 URL 和主键值。
假设C#有类似Java的SDK。以下是针对Java的内容:
从Azure函数连接到documentDB有两种方法。
使用SDK
DocumentClient documentClient = new DocumentClient( "SERVICE_ENDPOINT", "MASTER_KEY", ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
参考 - [https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-java-samples][1]。这里也有.Net示例。
绑定
@FunctionName("CosmosDBStore") @CosmosDBOutput(name = "database", databaseName = "db_name", collectionName = "col_name", connectionStringSetting = "AzureCosmosDBConnection")
请确保您的应用程序设置和local.settings.json(如果您想在本地测试)中都有一个名为"AzureCosmosDBConnection"的变量。
参考 - [https://learn.microsoft.com/zh-cn/azure/azure-functions/functions-bindings-cosmosdb-v2][1]
上述链接还包含C#示例。