从FunctionApp访问CosmosDB表

时间:2019-11-13 09:36:38

标签: java azure azure-cosmosdb

我正在尝试从From function app中读取一个表,但是没有遇到任何API可以使function app与CosmosDB表进行交互。

但是我发现这是什么:

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) 

但是此代码中存在编译时错误。

1 个答案:

答案 0 :(得分:0)

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

  1. 更新function.json。将表输入绑定添加到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"
  } ]
}
  1. 更新您的代码 一种。创建您要从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://docs.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();
    
    
    }
    
  2. 测试

enter image description here enter image description here