gpt4 book ai didi

java - 从 Function App 访问 Cosmos DB 表

转载 作者:行者123 更新时间:2023-12-01 21:25:01 26 4
gpt4 key购买 nike

我尝试从 From 函数应用读取表,但没有遇到任何允许函数应用与 CosmosDB 表交互的 API。

但是这是我发现的:

public HttpResponseMessage run(@HttpTrigger(name = "req", methods = { HttpMethod.GET,
HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS),@TableInput(name = "items",
tableName = "mytablename",
partitionKey = "myparkey",
connection = "myconnvarname") MyItem[] items, HttpRequestMessage<Optional<String>> request,
final ExecutionContext context)

但是这段代码存在编译时错误。

最佳答案

如果可以在Azure java函数中访问Azure Cosmos Table API,我们可以使用Azure Table Storage input binding访问 Azure Cosmos DB 表 API。例如

  1. 更新 function.json。将表输入绑定(bind)添加到 json 文件
{
"scriptFile" : "..\\testfun-1.0-SNAPSHOT.jar",
"entryPoint" : "testfun.Function.run",
"bindings" : [ {
"type" : "httpTrigger",
"direction" : "in",
"name" : "req",
"methods" : [ "GET", "POST" ]
}, {
"type" : "table",
"direction" : "in",
"name" : "users",
"connection" : "MyConn",// your Cosmos DB table API connection string
"tableName" : "User"// your table name
}, {
"type" : "http",
"direction" : "out",
"name" : "$return"
} ]
}
  • 更新您的代码A。创建一个要从 Cosmos DB 返回的类

     class User{

    public String PartitionKey;



    public String RowKey;
    public String Age;

    public String getPartitionKey() {
    return PartitionKey;
    }

    public void setPartitionKey(String partitionKey) {
    PartitionKey = partitionKey;
    }

    public String getRowKey() {
    return RowKey;
    }

    public void setRowKey(String rowKey) {
    RowKey = rowKey;
    }

    public String getAge() {
    return Age;
    }

    public void setAge(String age) {
    Age = age;
    }


    @Override
    public String toString() {
    return "User{" +
    "PartitionKey='" + PartitionKey + '\'' +
    ", RowKey='" + RowKey + '\'' +
    ", Age='" + Age + '\'' +
    '}';
    }


    }

    b.更新功能。更多详情请引用https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-table#input---java-example

    @FunctionName("HttpTrigger-Java")
    public HttpResponseMessage run(
    @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
    @TableInput(name = "users",
    tableName = "User",
    connection = "MyConn") User[] users,final ExecutionContext context) {
    context.getLogger().info("Java HTTP trigger processed a request.");


    return request.createResponseBuilder(HttpStatus.OK).body("Hello" + "\n" +users[0].toString()).build();


    }
  • 测试

  • enter image description here enter image description here

    关于java - 从 Function App 访问 Cosmos DB 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58834057/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com