лазурный космос documentdb api - PullRequest
       6

лазурный космос documentdb api

0 голосов
/ 14 октября 2019

Невозможно подключить космос БД. Получено исключение клиента документа.

package com.learn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.microsoft.azure.documentdb.ConnectionPolicy;
import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.Database;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;


@SpringBootApplication
@RestController
public class HelloCosmosApplication {

    public static void main(String[] args) {

        SpringApplication.run(HelloCosmosApplication.class, args);

    }

    private DocumentClient client;

    @RequestMapping("Connect")
    public String connectToDB() throws DocumentClientException {


             // Making the connection with COSMos DB account
            client = new DocumentClient("https://something-something.documents.azure.com:443/",
                    "someKeyShouldBeYourPrimaryKeyIfYouWantToPerformReadWriteOperation==",
                    new ConnectionPolicy(), ConsistencyLevel.Session);

            this.createDatabaseIfNotExists("dbname");




//        JSONParser parser = new JSONParser();
        // Use JSONObject for simple JSON and JSONArray for array of JSON.
//        JSONObject data = (JSONObject) parser
//                .parse(new FileReader("C:/STSTestWorkspace/HelloCosmos/src/main/resources/test.json"));


        //This one is added to take date and time.
//        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//        Date date = new Date();
//        data.put("id", date.toString());   // we are taking ID as a random value.



        return "Success";
}

    // Create Database
    private void createDatabaseIfNotExists(String databaseName) throws DocumentClientException {
        String databaseLink = String.format("/dbs/%s", databaseName);

        // Check to verify a database with the id=QMConnectivityDB does not exist
        try {
            client.readDatabase(databaseLink, null);
        } catch (DocumentClientException de) {
            // If the database does not exist, create a new database
            if (de.getStatusCode() == 404) {
                Database database = new Database();
                database.setId(databaseName);

//                client.createDatabase(database, null);
            } else {
                throw de;
            }
        }
    }
}

Получено во встроенной консоли при весенней загрузке:

Отображено "{[/ Connect]}" на общедоступный java.lang.String com. learn.HelloCosmosApplication.connectToDB () выдает com.microsoft.azure.documentdb.DocumentClientException

Я просто хочу установить соединение, достигнув существующей базы данных в облачном пространстве Azure. Благодаря.

1 Ответ

0 голосов
/ 15 октября 2019

На основании моего теста все работает нормально.

Вот мой пример:

    @RequestMapping({"/","/db"})
    @ResponseBody
    public String db() {
        String result = "";

        try {
            DocumentClient documentClient = new DocumentClient(
                    "https://jackdocumentdb.documents.azure.com:443/",
                    "hcaqayqxz3Jxc*******0v2tkDplDSdax3iW5n64bgfSg==",
                    ConnectionPolicy.GetDefault(),
                    ConsistencyLevel.Session);

            Database myDatabase = new Database();
            myDatabase.setId("database");

            try{
                documentClient.readDatabase("dbs/database",null);
            }catch (Exception e){
                logger.info(e.toString());
                myDatabase = documentClient.createDatabase(myDatabase, null).getResource();
            }

            DocumentCollection myCollection = new DocumentCollection();
            myCollection.setId("collection");

            try{
                documentClient.readCollection("dbs/database/colls/collection",null);
            }catch (Exception e){
                logger.info(e.toString());
                RequestOptions requestOptions = new RequestOptions();
                requestOptions.setOfferThroughput(400);
                myCollection = documentClient.createCollection(
                        "dbs/database", myCollection, requestOptions)
                        .getResource();
            }

            result = myCollection.getSelfLink();

            documentClient.close();

        } catch (Exception e) {
            logger.info(e.toString());
        }
        return result;
    }

Консольные выходы:

2019-10-15 14:11:56.552  INFO 21432 --- [nio-8080-exec-4] c.m.azure.documentdb.DocumentClient      : Initializing DocumentClient with serviceEndpoint [https://jackdocumentdb.documents.azure.com:443/], ConnectionPolicy [ConnectionPolicy [requestTimeout=60, directRequestTimeout5, mediaRequestTimeout=300, connectionMode=Gateway, mediaReadMode=Buffered, maxPoolSize=400, idleConnectionTimeout=60, userAgentSuffix=, retryOptions=com.microsoft.azure.documentdb.RetryOptions@1f83947e, enableEndpointDiscovery=true, preferredLocations=null, usingMultipleWriteLocations=false, handleServiceUnavailableFromProxy=false]], ConsistencyLevel [Session]
2019-10-15 14:11:58.548  INFO 21432 --- [nio-8080-exec-4] c.e.viever.controller.MainController     : com.microsoft.azure.documentdb.DocumentClientException: Message: {"Errors":["Resource Not Found"]}
ActivityId: eb11a07b-2d34-4676-a930-f9ce48be03bb, Request URI: /apps/4a0a03b0-c5b6-4776-bb7e-7446131c8e1d/services/2704eecf-4c3d-43f8-96ff-9187974116c8/partitions/b3cde68f-b9f0-4ebc-8632-f2c7b75098fe/replicas/132155818573058919s, RequestStats: 
RequestStartTime: 2019-10-15T06:11:58.3492376Z, RequestEndTime: 2019-10-15T06:11:58.3492376Z,  Number of regions attempted:1
ResponseTime: 2019-10-15T06:11:58.3492376Z, StoreResult: StorePhysicalAddress: rntbd://10.0.0.25:19700/apps/4a0a03b0-c5b6-4776-bb7e-7446131c8e1d/services/2704eecf-4c3d-43f8-96ff-9187974116c8/partitions/b3cde68f-b9f0-4ebc-8632-f2c7b75098fe/replicas/132155818573058919s, LSN: 15, GlobalCommittedLsn: 15, PartitionKeyRangeId: , IsValid: True, StatusCode: 404, SubStatusCode: 0, RequestCharge: 1, ItemLSN: -1, SessionToken: -1#15, UsingLocalLSN: False, TransportException: null, ResourceType: Database, OperationType: Read
ResponseTime: 2019-10-15T06:11:58.3492376Z, StoreResult: StorePhysicalAddress: rntbd://10.0.0.23:19700/apps/4a0a03b0-c5b6-4776-bb7e-7446131c8e1d/services/2704eecf-4c3d-43f8-96ff-9187974116c8/partitions/b3cde68f-b9f0-4ebc-8632-f2c7b75098fe/replicas/132155923342596657s, LSN: -1, GlobalCommittedLsn: -1, PartitionKeyRangeId: , IsValid: False, StatusCode: 410, SubStatusCode: 0, RequestCharge: 0, ItemLSN: -1, SessionToken: , UsingLocalLSN: False, TransportException: null, ResourceType: Database, OperationType: Read
ResponseTime: 2019-10-15T06:11:58.3492376Z, StoreResult: StorePhysicalAddress: rntbd://10.0.0.19:17000/apps/4a0a03b0-c5b6-4776-bb7e-7446131c8e1d/services/2704eecf-4c3d-43f8-96ff-9187974116c8/partitions/b3cde68f-b9f0-4ebc-8632-f2c7b75098fe/replicas/132155818573058918s, LSN: 15, GlobalCommittedLsn: 15, PartitionKeyRangeId: , IsValid: True, StatusCode: 404, SubStatusCode: 0, RequestCharge: 1, ItemLSN: -1, SessionToken: -1#15, UsingLocalLSN: False, TransportException: null, ResourceType: Database, OperationType: Read
, SDK: Microsoft.Azure.Documents.Common/2.7.0, StatusCode: NotFound
2019-10-15 14:11:59.364  INFO 21432 --- [nio-8080-exec-4] c.e.viever.controller.MainController     : com.microsoft.azure.documentdb.DocumentClientException: Message: {"Errors":["Resource Not Found"]}
ActivityId: a87315f9-b2de-4c88-b11e-d02f73434bd3, Request URI: /apps/4a0a03b0-c5b6-4776-bb7e-7446131c8e1d/services/2704eecf-4c3d-43f8-96ff-9187974116c8/partitions/b3cde68f-b9f0-4ebc-8632-f2c7b75098fe/replicas/132155933903772782s, RequestStats: 
RequestStartTime: 2019-10-15T06:11:58.7092159Z, RequestEndTime: 2019-10-15T06:11:58.7092159Z,  Number of regions attempted:1
ResponseTime: 2019-10-15T06:11:58.7092159Z, StoreResult: StorePhysicalAddress: rntbd://10.0.0.28:19700/apps/4a0a03b0-c5b6-4776-bb7e-7446131c8e1d/services/2704eecf-4c3d-43f8-96ff-9187974116c8/partitions/b3cde68f-b9f0-4ebc-8632-f2c7b75098fe/replicas/132155933903772782s, LSN: 16, GlobalCommittedLsn: 16, PartitionKeyRangeId: , IsValid: True, StatusCode: 404, SubStatusCode: 0, RequestCharge: 1, ItemLSN: -1, SessionToken: -1#16, UsingLocalLSN: False, TransportException: null, ResourceType: Collection, OperationType: Read
ResponseTime: 2019-10-15T06:11:58.7092159Z, StoreResult: StorePhysicalAddress: rntbd://10.0.0.19:17000/apps/4a0a03b0-c5b6-4776-bb7e-7446131c8e1d/services/2704eecf-4c3d-43f8-96ff-9187974116c8/partitions/b3cde68f-b9f0-4ebc-8632-f2c7b75098fe/replicas/132155818573058918s, LSN: 16, GlobalCommittedLsn: 16, PartitionKeyRangeId: , IsValid: True, StatusCode: 404, SubStatusCode: 0, RequestCharge: 1, ItemLSN: -1, SessionToken: -1#16, UsingLocalLSN: False, TransportException: null, ResourceType: Collection, OperationType: Read
, SDK: Microsoft.Azure.Documents.Common/2.7.0, StatusCode: NotFound
2019-10-15 14:12:00.042  INFO 21432 --- [nio-8080-exec-4] c.m.azure.documentdb.DocumentClient      : Closing DocumentClient

В выходных данных я получаю два исключения, оба из которых не найдены, исключение. Это правильно, потому что это новый документ БД, и ничего не было создано.

И, наконец, я вижу, что целевая база данных и целевая коллекция создаются из портала:

enter image description here


Предложения:

Вы можете проверить подробное исключение, чтобы увидеть, что именно является причиной вашей проблемы. Может быть, это просто проблема с подключением.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...