// Create Async client.
// Building an async client is still a sync operation.
CosmosAsyncClient client = new CosmosClientBuilder()
.endpoint("your.hostname")
.key("yourmasterkey")
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.buildAsyncClient();
// Create database with specified name
client.createDatabaseIfNotExists("YourDatabaseName")
.flatMap(databaseResponse -> {
testDatabaseAsync = client.getDatabase("YourDatabaseName");
// Container properties - name and partition key
CosmosContainerProperties containerProperties =
new CosmosContainerProperties("YourContainerName", "/id");
// Provision manual throughput
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
// Create container
return database.createContainerIfNotExists(containerProperties, throughputProperties);
}).flatMap(containerResponse -> {
testContainerAsync = database.getContainer("YourContainerName");
return Mono.empty();
}).subscribe();
ConnectionPolicy defaultPolicy = ConnectionPolicy.defaultPolicy();
// Setting the preferred location to Azure Cosmos DB Account region
defaultPolicy.preferredLocations(Lists.newArrayList("Your Account Location"));
// Create async client
// <CreateAsyncClient>
client = new CosmosClientBuilder()
.endpoint("your.hostname")
.key("yourmasterkey")
.connectionPolicy(defaultPolicy)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.build();
// Create database with specified name
client.createDatabaseIfNotExists("YourDatabaseName")
.flatMap(databaseResponse -> {
database = databaseResponse.database();
// Container properties - name and partition key
CosmosContainerProperties containerProperties =
new CosmosContainerProperties("YourContainerName", "/id");
// Create container with specified properties & provisioned throughput
return database.createContainerIfNotExists(containerProperties, 400);
}).flatMap(containerResponse -> {
container = containerResponse.container();
return Mono.empty();
}).subscribe();
ConnectionPolicy defaultPolicy = ConnectionPolicy.GetDefault();
// Setting the preferred location to Azure Cosmos DB Account region
defaultPolicy.setPreferredLocations(Lists.newArrayList("Your Account Location"));
// Create document client
// <CreateDocumentClient>
client = new DocumentClient("your.hostname", "your.masterkey", defaultPolicy, ConsistencyLevel.Eventual)
// Create database with specified name
Database databaseDefinition = new Database();
databaseDefinition.setId("YourDatabaseName");
ResourceResponse<Database> databaseResourceResponse = client.createDatabase(databaseDefinition, new RequestOptions());
// Read database with specified name
String databaseLink = "dbs/YourDatabaseName";
databaseResourceResponse = client.readDatabase(databaseLink, new RequestOptions());
Database database = databaseResourceResponse.getResource();
// Create container with specified name
DocumentCollection documentCollection = new DocumentCollection();
documentCollection.setId("YourContainerName");
documentCollection = client.createCollection(database.getSelfLink(), documentCollection, new RequestOptions()).getResource();
// Create Async client.
// Building an async client is still a sync operation.
AsyncDocumentClient client = new Builder()
.withServiceEndpoint("your.hostname")
.withMasterKeyOrResourceToken("yourmasterkey")
.withConsistencyLevel(ConsistencyLevel.Eventual)
.build();
// Create database with specified name
Database database = new Database();
database.setId("YourDatabaseName");
client.createDatabase(database, new RequestOptions())
.flatMap(databaseResponse -> {
// Collection properties - name and partition key
DocumentCollection documentCollection = new DocumentCollection();
documentCollection.setId("YourContainerName");
documentCollection.setPartitionKey(new PartitionKeyDefinition("/id"));
// Create collection
return client.createCollection(databaseResponse.getResource().getSelfLink(), documentCollection, new RequestOptions());
}).subscribe();
項目操作
下列程式碼片段顯示 4.0、3.x.x 非同步、2.x.x 同步和 2.x.x 非同步 API 在如何執行項目作業方面有何差異:
ChangeFeedProcessor changeFeedProcessorInstance =
new ChangeFeedProcessorBuilder()
.hostName(hostName)
.feedContainer(feedContainer)
.leaseContainer(leaseContainer)
.handleChanges((List<JsonNode> docs) -> {
logger.info("--->setHandleChanges() START");
for (JsonNode document : docs) {
try {
//Change Feed hands the document to you in the form of a JsonNode
//As a developer you have two options for handling the JsonNode document provided to you by Change Feed
//One option is to operate on the document in the form of a JsonNode, as shown below. This is great
//especially if you do not have a single uniform data model for all documents.
logger.info("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(document));
//You can also transform the JsonNode to a POJO having the same structure as the JsonNode,
//as shown below. Then you can operate on the POJO.
CustomPOJO pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO.class);
logger.info("----=>id: " + pojo_doc.getId());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
logger.info("--->handleChanges() END");
})
.buildChangeFeedProcessor();
// ...
changeFeedProcessorInstance.start()
.subscribeOn(Schedulers.elastic())
.subscribe();
ChangeFeedProcessor changeFeedProcessorInstance =
ChangeFeedProcessor.Builder()
.hostName(hostName)
.feedContainer(feedContainer)
.leaseContainer(leaseContainer)
.handleChanges((List<CosmosItemProperties> docs) -> {
logger.info("--->setHandleChanges() START");
for (CosmosItemProperties document : docs) {
try {
// You are given the document as a CosmosItemProperties instance which you may
// cast to the desired type.
CustomPOJO pojo_doc = document.getObject(CustomPOJO.class);
logger.info("----=>id: " + pojo_doc.id());
} catch (Exception e) {
e.printStackTrace();
}
}
logger.info("--->handleChanges() END");
})
.build();
// ...
changeFeedProcessorInstance.start()
.subscribeOn(Schedulers.elastic())
.subscribe();
自 Java SDK v2 同步起不支援此功能。
自 Java SDK v2 非同步起不支援此功能。
容器層級存留時間 (TTL)
下列程式碼片段顯示 4.0、3.x.x 非同步、2.x.x 同步和 2.x.x 非同步 API 在如何為容器中的資料建立存留時間方面有何差異:
CosmosAsyncContainer container;
// Create a new container with TTL enabled with default expiration value
CosmosContainerProperties containerProperties = new CosmosContainerProperties("myContainer", "/myPartitionKey");
containerProperties.setDefaultTimeToLiveInSeconds(90 * 60 * 60 * 24);
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
database.createContainerIfNotExists(containerProperties, throughputProperties).block();
container = database.getContainer("myContainer");
CosmosContainer container;
// Create a new container with TTL enabled with default expiration value
CosmosContainerProperties containerProperties = new CosmosContainerProperties("myContainer", "/myPartitionKey");
containerProperties.defaultTimeToLive(90 * 60 * 60 * 24);
container = database.createContainerIfNotExists(containerProperties, 400).block().container();
DocumentCollection documentCollection;
// Create a new container with TTL enabled with default expiration value
documentCollection.setDefaultTimeToLive(90 * 60 * 60 * 24);
documentCollection = client.createCollection(database.getSelfLink(), documentCollection, new RequestOptions()).getResource();
DocumentCollection collection = new DocumentCollection();
// Create a new container with TTL enabled with default expiration value
collection.setDefaultTimeToLive(90 * 60 * 60 * 24);
collection = client
.createCollection(database.getSelfLink(), documentCollection, new RequestOptions())
.toBlocking()
.single()
.getResource();
項目層級存留時間 (TTL)
下列程式碼片段顯示 4.0、3.x.x 非同步、2.x.x 同步和 2.x.x 非同步 API 在如何為項目建立存留時間方面有何差異:
// Include a property that serializes to "ttl" in JSON
class SalesOrder
{
private String id;
private String customerId;
private Integer ttl;
public SalesOrder(String id, String customerId, Integer ttl) {
this.id = id;
this.customerId = customerId;
this.ttl = ttl;
}
public String getId() {return this.id;}
public void setId(String new_id) {this.id = new_id;}
public String getCustomerId() {return this.customerId;}
public void setCustomerId(String new_cid) {this.customerId = new_cid;}
public Integer getTtl() {return this.ttl;}
public void setTtl(Integer new_ttl) {this.ttl = new_ttl;}
//...
}
// Set the value to the expiration in seconds
SalesOrder salesOrder = new SalesOrder(
"SO05",
"CO18009186470",
60 * 60 * 24 * 30 // Expire sales orders in 30 days
);
// Include a property that serializes to "ttl" in JSON
public class SalesOrder
{
private String id;
private String customerId;
private Integer ttl;
public SalesOrder(String id, String customerId, Integer ttl) {
this.id = id;
this.customerId = customerId;
this.ttl = ttl;
}
public String id() {return this.id;}
public SalesOrder id(String new_id) {this.id = new_id; return this;}
public String customerId() {return this.customerId; return this;}
public SalesOrder customerId(String new_cid) {this.customerId = new_cid;}
public Integer ttl() {return this.ttl;}
public SalesOrder ttl(Integer new_ttl) {this.ttl = new_ttl; return this;}
//...
}
// Set the value to the expiration in seconds
SalesOrder salesOrder = new SalesOrder(
"SO05",
"CO18009186470",
60 * 60 * 24 * 30 // Expire sales orders in 30 days
);
Document document = new Document();
document.setId("YourDocumentId");
document.setTimeToLive(60 * 60 * 24 * 30 ); // Expire document in 30 days
ResourceResponse<Document> documentResourceResponse = client.createDocument(documentCollection.getSelfLink(), document,
new RequestOptions(), true);
Document responseDocument = documentResourceResponse.getResource();
Document document = new Document();
document.setId("YourDocumentId");
document.setTimeToLive(60 * 60 * 24 * 30 ); // Expire document in 30 days
ResourceResponse<Document> documentResourceResponse = client.createDocument(documentCollection.getSelfLink(), document,
new RequestOptions(), true).toBlocking().single();
Document responseDocument = documentResourceResponse.getResource();
下一步
建置 JAVA 應用程式以使用 V4 SDK 管理 Azure Cosmos DB for NoSQL 資料