java - 天蓝色 cosmos 文档数据库 api
问题描述
无法连接 cosmos DB。得到文档客户端异常。
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;
}
}
}
}
在 spring-boot 嵌入式控制台中得到了这个:
将“{[/Connect]}”映射到公共 java.lang.String com.learn.HelloCosmosApplication.connectToDB() 会抛出 com.microsoft.azure.documentdb.DocumentClientException
我只想通过访问 Azure cosmos 云中的现有数据库来建立连接。谢谢。
解决方案
根据我的测试,一切正常。
这是我的示例:
@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
在输出中,我得到了两个都没有发现异常的异常。这是正确的,因为它是一个新的文档数据库,并且没有创建任何内容。
最后,我可以看到目标数据库和目标集合是从门户创建的:
建议:
您可以检查详细的异常以查看究竟是什么导致了您的问题。也许这只是一个连接问题。
推荐阅读
- git - 如何解决“错误:无法合并,因为您有未合并的文件。”?
- powershell - Try Catch - 如何捕捉错误但继续?
- django - 将请求用户传递给 Django 中的模型表单
- ios - ipad 上键盘扩展限制的错误
- javascript - 我正在尝试在我的演示反应 redux 应用程序中实现 Api 当我单击事件时我的 Api 调用两次
- python - 无一例外地在python中失败AWS lambda
- javascript - 使用时刻将字符串日期和时间转换为基于时区的 UTC
- android - 如何禁用功能:aosp_car_x86_64-userdebug(android 11 汽车模拟器)中的 android.hardware.bluetooth
- azure - ADF Dynamic Expression - concat/if missing period
- amazon-web-services - Trigger AWS Lambda once SQS fifo queue is not empty