Java Azure正在连接到Cosmos数据库

nxowjjhe  于 2023-03-09  发布在  Java
关注(0)|答案(1)|浏览(139)

我正在构建一个Java Azure函数,我想连接到我的Cosmos数据库并在其中执行CRUD操作。无论我现在做什么,我都无法在运行函数时连接到数据库。如果我尝试使用@CosmosDBOutput和Document进行连接,我可以上传到数据库,但是我需要把函数分离出来。下面是我的主处理程序(使用@CosmosDBOutput和Document工作和上传):

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import com.microsoft.azure.documentdb.Document;

public class Handler {

    @FunctionName("HttpHandler")
    public HttpResponseMessage runHttp(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> req, 
            @CosmosDBOutput(name = "database", databaseName = "hyperscalerapi-cosmos-dev", 
            collectionName = "Items", connectionStringSetting = "cosmosDBConnectionString")
            OutputBinding<String> outputItem, final ExecutionContext context) {
        try {
            
            // request to String (payload)
            String payload = req.getBody().get();

            Document document = new Document(payload);
            document.setId(context.getInvocationId().toString());
            outputItem.setValue(document.toString());
            context.getLogger().info("\nAdded payload: " + payload + 
                                    "\nWith ID: " + context.getInvocationId().toString() + "\nTo CosmosDB\n");
            
            return req.createResponseBuilder(HttpStatus.OK).body("Data logged").build();
        } catch (Exception e) {
            // log the exception
            context.getLogger().severe(e.toString());
            return req.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred").build();
        }
    }
}

下面是我要做的代码,其中包括处理程序以及我的CosmosOperation.java类,我正尝试使用该类连接到数据库:

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import com.microsoft.azure.documentdb.Document;

public class Handler {

    @FunctionName("HttpHandler")
    public HttpResponseMessage runHttp(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> req, final ExecutionContext context) {
        try {
            
            // request to String (payload)
            String payload = req.getBody().get();

            // Create in Cosmos
            CosmosOperation p = new CosmosOperation();
            p.create(payload, context);

            return req.createResponseBuilder(HttpStatus.OK).body("Data logged").build();
        } catch (Exception e) {
            // log the exception
            context.getLogger().severe(e.toString());
            return req.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred").build();
        }
    }
}

和CosmosOperation.java类:

import com.microsoft.azure.functions.annotation.*;
    import com.microsoft.azure.functions.*;
    import java.util.*;
    import java.util.logging.*;
    import com.azure.cosmos.*;
    import com.azure.cosmos.models.*;
    import com.azure.cosmos.util.CosmosPagedIterable;
    import com.microsoft.azure.documentdb.Document;
    //import com.azure.cosmos.examples.common.AccountSettings;
    
    /**
     * Azure Functions in Java with Cosmos DB Trigger.
     */
    public class CosmosOperation {
        public CosmosClient client;
        private final String databaseName = "hyperscalerapi-cosmos-dev";
        private CosmosDatabase database;
        public CosmosContainer container;
        private final String containerName = "Items";
    
        public CosmosOperation() {
            try {
                client = new CosmosClientBuilder()
                            .endpoint("This is where my CosmosDB endpoint is")
                            .key("This is where my CosmosDB Primary Key is")
                            .consistencyLevel(ConsistencyLevel.EVENTUAL)
                            .contentResponseOnWriteEnabled(true)
                            .buildClient();
            } catch (Exception e) {
                System.out.println("----------------------------------------------------------");
                System.out.println(e);
                System.out.println("----------------------------------------------------------");
            }
        }
    public void create(String payload, final ExecutionContext context) {
        container.createItem(payload, new PartitionKey(context.getInvocationId().toString()), new CosmosItemRequestOptions());
    }
}

这是我得到的主要错误。我知道端点和键是正确的,因为它们都在我在工作处理程序中使用的连接字符串中:

java.lang.RuntimeException: Client initialization failed. Check if the endpoint is reachable and if your auth token is valid. More info: https://aka.ms/cosmosdb-tsg-service-unavailable-java

然而,我也收到了其中的一些错误,但我认为它们目前并不重要:

java.lang.NoSuchMethodError: 'void io.netty.handler.codec.http.HttpClientCodec.<init>(int, int, int, boolean, boolean, int, boolean, boolean)'
gojuced7

gojuced71#

以下是您为 CosmosOperation.java 类共享的代码的观察结果,该类负责将您的代码连接到Cosmos DB并创建项目/文档。
1.假设数据库hyperscalerapi-cosmos-dev和容器Items已经在Cosmos DB帐户中创建。
1.为了在各自的容器中创建项目/文档,我们使用CosmosContainer类的CreateItem()。您已经使用了相同的container对象,但尚未初始化。要初始化CosmosContainer类的container对象,您可以参考以下示例代码。
CosmosDatabase db = client.getDatabase("hyperscalerapi-cosmos-dev"); CosmosContainer customContainer = db.getContainer("Items");
您可以参考document
下面是我尝试连接到Cosmos DB的示例代码:

CosmosClient client;
        final String databaseName = "hyperscalerapi-cosmos-dev";
        CosmosDatabase database;
        final String containerName = "Items";
        try {
            client = new CosmosClientBuilder()       
            .endpoint("Cosmos DB endpoint")  
            .key("Cosmos DB primary key")
            .consistencyLevel(ConsistencyLevel.EVENTUAL)
            .contentResponseOnWriteEnabled(true)
            .buildClient();
            //get database id or initialize the CosmosDatabase object
            CosmosDatabase db =  client.getDatabase("hyperscalerapi-cosmos-dev");
            //initialization of the CosmosDatabase object
            CosmosContainer container = db.getContainer("Items");
            //Sample class used to create item in Cosmos DB
            Product p = new Product();
            p.setId("4");
            p.setName("ProductName4");
            p.setCategory("Category2");
            container.createItem(p,new PartitionKey(p.getCategory()),new CosmosItemRequestOptions());
        } catch (Exception e) {
            System.out.println("----------------------------------------------------------");
            System.out.println(e);
            System.out.println("----------------------------------------------------------");
        }

示例类产品.java

class Product  {  
String id;  
String name;  
String category;  
public String getId() {  
    return id;  
    }
public void setId(String id) {  
    this.id = id;  
    }
public String getName() {  
    return name;
    }
public void setName(String name) {  
    this.name = name;
    } 
public String getCategory() {  
    return category;  
    }  
public void setCategory(String category) {  
    this.category = category;  
    }  
 }

相关问题