Introduction to Couchbase SDK for Java – Couchbase SDK for Java简介

最后修改: 2016年 7月 3日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this introduction to the Couchbase SDK for Java, we demonstrate how to interact with a Couchbase document database, covering basic concepts such as creating a Couchbase environment, connecting to a cluster, opening data buckets, using the basic persistence operations, and working with document replicas.

在这篇关于Couchbase SDK for Java的介绍中,我们演示了如何与Couchbase文档数据库进行交互,涵盖了一些基本的概念,如创建Couchbase环境、连接到集群、打开数据桶、使用基本的持久化操作以及与文档副本的工作。

2. Maven Dependencies

2.Maven的依赖性

If you are using Maven, add the following to your pom.xml file:

如果你使用的是Maven,请在你的pom.xml文件中添加以下内容。

<dependency>
    <groupId>com.couchbase.client</groupId>
    <artifactId>java-client</artifactId>
    <version>2.2.6</version>
</dependency>

3. Getting Started

3.入门

The SDK provides the CouchbaseEnvironment interface and an implementation class DefaultCouchbaseEnvironment containing default settings for managing access to clusters and buckets. The default environment settings can be overridden if necessary, as we will see in section 3.2.

SDK提供了CouchbaseEnvironment接口和一个实现类DefaultCouchbaseEnvironment,包含了管理集群和桶的访问的默认设置。如有必要,默认的环境设置可以被重写,我们将在第3.2节中看到。

Important: The official Couchbase SDK documentation cautions users to ensure that only one CouchbaseEnvironment is active in the JVM, since the use of two or more may result in unpredictable behavior.

重要的是:官方Couchbase SDK文档提醒用户确保JVM中只有一个CouchbaseEnvironment是活动的,因为使用两个或更多的环境可能会导致不可预测的行为。

3.1. Connecting to a Cluster With a Default Environment

3.1.连接到具有默认环境的集群

To have the SDK automatically create a CouchbaseEnvironment with default settings and associate it with our cluster, we can connect to the cluster simply by providing the IP address or hostname of one or more nodes in the cluster.

为了让SDK自动创建一个具有默认设置的CouchbaseEnvironment并与我们的集群相关联,我们可以通过提供集群中一个或多个节点的IP地址或主机名来连接到集群。

In this example, we connect to a single-node cluster on our local workstation:

在这个例子中,我们在本地工作站上连接到一个单节点集群。

Cluster cluster = CouchbaseCluster.create("localhost");

To connect to a multi-node cluster, we would specify at least two nodes in case one of them is unavailable when the application attempts to establish the connection:

要连接到一个多节点集群,我们至少要指定两个节点,以防在应用程序试图建立连接时其中一个节点不可用。

Cluster cluster = CouchbaseCluster.create("192.168.4.1", "192.168.4.2");

Note: It is not necessary to specify every node in the cluster when creating the initial connection. The CouchbaseEnvironment will query the cluster once the connection is established in order to discover the remaining nodes (if any).

注意:在创建初始连接时,没有必要指定集群中的每个节点。一旦连接建立,CouchbaseEnvironment将查询集群,以发现剩余的节点(如果有的话)。

3.2. Using a Custom Environment

3.2.使用自定义环境

If your application requires fine tuning of any of the settings provided by DefaultCouchbaseEnvironment, you can create a custom environment and then use that environment when connecting to your cluster.

如果你的应用程序需要对DefaultCouchbaseEnvironment提供的任何设置进行微调,你可以创建一个自定义环境,然后在连接到集群时使用该环境。

Here’s an example that connects to a single-node cluster using a custom CouchbaseEnvironment with a ten-second connection timeout and a three-second key-value lookup timeout:

这里有一个例子,使用一个自定义的CouchbaseEnvironment连接到一个单节点集群,连接超时10秒,键值查询超时3秒。

CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
  .connectTimeout(10000)
  .kvTimeout(3000)
  .build();
Cluster cluster = CouchbaseCluster.create(env, "localhost");

And to connect to a multi-node cluster with the custom environment:

并用自定义环境连接到一个多节点集群。

Cluster cluster = CouchbaseCluster.create(env,
  "192.168.4.1", "192.168.4.2");

3.3. Opening a Bucket

3.3.打开一个水桶

Once you have connected to the Couchbase cluster, you can open one or more buckets.

一旦你连接到Couchbase集群,你可以打开一个或多个桶。

When you first set up a Couchbase cluster, the installation package automatically creates a bucket named “default” with a blank password.

当你第一次建立Couchbase集群时,安装包会自动创建一个名为“default”的桶,并设置一个空白密码。

Here’s one way to open the “default” bucket when it has a blank password:

这里有一个方法,当“default”桶有一个空白密码时,可以打开它。

Bucket bucket = cluster.openBucket();

You can also specify the bucket name when opening it:

你也可以在打开水桶时指定水桶的名称。

Bucket bucket = cluster.openBucket("default");

For any other bucket with a blank password, you must supply the bucket name:

对于任何其他有空白密码的桶,你必须提供桶的名称。

Bucket myBucket = cluster.openBucket("myBucket");

To open a bucket that has a non-blank password, you must supply the bucket name and password:

要打开一个有非空白密码的桶,你必须提供桶的名称密码。

Bucket bucket = cluster.openBucket("bucketName", "bucketPassword");

4. Persistence Operations

4.持久性操作

In this section, we show how to perform CRUD operations in Couchbase. In our examples, we will be working with simple JSON documents representing a person, as in this sample document:

在本节中,我们将展示如何在Couchbase中执行CRUD操作。在我们的例子中,我们将处理代表一个人的简单JSON文档,就像这个样本文档一样。

{
  "name": "John Doe",
  "type": "Person",
  "email": "john.doe@mydomain.com",
  "homeTown": "Chicago"
}

The “type” attribute is not required, however it is common practice to include an attribute specifying the document type in case one decides to store multiple types in the same bucket.

“type”属性不是必须的,但是通常的做法是包括一个指定文档类型的属性,以备决定在同一个桶中存储多种类型。

4.1. Document IDs

4.1.文件编号

Each document stored in Couchbase is associated with an id that is unique to the bucket in which the document is being stored. The document id is analogous to the primary key column in a traditional relational database row.

每个存储在Couchbase中的文档都与一个id相关联,这个id对于存储该文档的桶来说是唯一的。文档的id类似于传统关系型数据库行中的主键列。

Document id values must be UTF-8 strings of 250 or fewer bytes.

文档id值必须是250或更少字节的UTF-8字符串。

Since Couchbase does not provide a mechanism for automatically generating the id on insertion, we must provide our own.

由于Couchbase没有提供一个在插入时自动生成id的机制,我们必须提供我们自己的。

Common strategies for generating ids include key-derivation using a natural key, such as the “email” attribute shown in our sample document, and the use of UUID strings.

生成ids的常见策略包括使用自然键的键衍生,例如我们的样本文档中显示的“email”属性,以及使用UID字符串。

For our examples, we will generate random UUID strings.

对于我们的例子,我们将生成随机的UID字符串。

4.2. Inserting a Document

4.2.插入一个文件

Before we can insert a new document into our bucket, we must first create an instance of JSONObject containing the document’s contents:

在我们将一个新的文档插入到我们的桶中之前,我们必须首先创建一个包含文档内容的JSONObject实例。

JsonObject content = JsonObject.empty()
  .put("name", "John Doe")
  .put("type", "Person")
  .put("email", "john.doe@mydomain.com")
  .put("homeTown", "Chicago");

Next, we create a JSONDocument object consisting of an id value and the JSONObject:

接下来,我们创建一个JSONDocument对象,由一个id值和JSONObject组成。

String id = UUID.randomUUID().toString();
JsonDocument document = JsonDocument.create(id, content);

To add a new document to the bucket, we use the insert method:

为了向桶中添加一个新的文档,我们使用insert方法。

JsonDocument inserted = bucket.insert(document);

The JsonDocument returned contains all of the properties of the original document, plus a value known as the “CAS” (compare-and-swap) value that Couchbase uses for version tracking.

返回的JsonDocument包含了原始文档的所有属性,加上一个被称为“CAS”(compare-and-swap)的值,Couchbase使用这个值来进行版本跟踪。

If a document with the supplied id already exists in the bucket, Couchbase throws a DocumentAlreadyExistsException.

如果一个具有提供的id的文档已经存在于桶中,Couchbase会抛出一个DocumentAlreadyExistsException

We can also use the upsert method, which will either insert the document (if the id is not found) or update the document (if the id is found):

我们还可以使用upsert方法,它将插入文档(如果没有找到id)或更新文档(如果找到id)。

JsonDocument upserted = bucket.upsert(document);

4.3. Retrieving a Document

4.3.检索一个文件

To retrieve a document by its id, we use the get method:

为了通过id检索一个文档,我们使用get方法。

JsonDocument retrieved = bucket.get(id);

If no document exists with the given id, the method returns null.

如果没有给定id的文档存在,该方法返回null

4.4. Updating or Replacing a Document

4.4.更新或替换一个文件

We can update an existing document using the upsert method:

我们可以使用upsert方法更新一个现有的文档。

JsonObject content = document.content();
content.put("homeTown", "Kansas City");
JsonDocument upserted = bucket.upsert(document);

As we mentioned in section 4.2, upsert will succeed whether a document with the given id was found or not.

正如我们在第4.2节中提到的,无论是否找到具有给定id的文档,upsert都将成功。

If enough time has passed between when we originally retrieved the document and our attempt to upsert the revised document, there is a possibility that the original document will have been deleted from the bucket by another process or user.

如果从我们最初检索文件到我们试图上载修改后的文件之间有足够的时间,那么原始文件有可能已经被另一个进程或用户从桶中删除。

If we need to guard against this scenario in our application, we can instead use the replace method, which fails with a DocumentDoesNotExistException if a document with the given id is not found in Couchbase:

如果我们需要在我们的应用程序中防范这种情况,我们可以使用replace方法,如果在Couchbase中没有找到具有给定id的文档,该方法会以DocumentDoesNotExistException失败。

JsonDocument replaced = bucket.replace(document);

4.5. Deleting a Document

4.5.删除一个文件

To delete a Couchbase document, we use the remove method:

要删除一个Couchbase文档,我们使用remove方法。

JsonDocument removed = bucket.remove(document);

You may also remove by id:

你也可以通过id删除。

JsonDocument removed = bucket.remove(id);

The JsonDocument object returned has only the id and CAS properties set; all other properties (including the JSON content) are removed from the returned object.

返回的JsonDocument对象只有idCAS属性被设置;所有其他属性(包括JSON内容)都从返回的对象中删除。

If no document exists with the given id, Couchbase throws a DocumentDoesNotExistException.

如果没有给定id的文档存在,Couchbase会抛出一个DocumentDoesNotExistException

5. Working With Replicas

5.使用复制的工作

This section discusses Couchbase’s virtual bucket and replica architecture and introduces a mechanism for retrieving a replica of a document in the event that a document’s primary node is unavailable.

本节讨论了Couchbase的虚拟桶和副本架构,并介绍了在文档的主节点不可用的情况下检索文档副本的机制。

5.1. Virtual Buckets and Replicas

5.1.虚拟桶和复制品

Couchbase distributes a bucket’s documents across a collection of 1024 virtual buckets, or vbuckets, using a hashing algorithm on the document id to determine the vbucket in which to store each document.

Couchbase将一个桶的文档分布在1024个虚拟桶的集合中,或称vbuckets,使用文档id上的散列算法来确定每个文档的vbucket存储位置。

Each Couchbase bucket can also be configured to maintain one or more replicas of each vbucket. Whenever a document is inserted or updated and written to its vbucket, Couchbase initiates a process to replicate the new or updated document to its replica vbucket.

每个Couchbase桶也可以被配置为维护每个vbucket的一个或多个replicas。每当一个文档被插入或更新并写入它的vbucket,Couchbase就会启动一个进程,将新的或更新的文档复制到它的replica vbucket

In a multi-node cluster, Couchbase distributes vbuckets and replica vbuckets among all the data nodes in the cluster. A vbucket and its replica vbucket are kept on separate data nodes in order to achieve a certain measure of high-availability.

在一个多节点集群中,Couchbase将vbucketsreplica vbuckets分布在集群中所有的数据节点上。一个vbucket和它的replica vbucket被保存在不同的数据节点上,以实现一定程度的高可用性。

5.2. Retrieving a Document From a Replica

5.2.从副本中检索文件

When retrieving a document by its id, if the document’s primary node is down or otherwise unreachable due to a network error, Couchbase throws an exception.

当通过id检索一个文档时,如果该文档的主节点由于网络错误而宕机或无法访问,Couchbase会抛出一个异常。

You can have your application catch the exception and attempt to retrieve one or more replicas of the document using the getFromReplica method.

你可以让你的应用程序捕捉到这个异常,并尝试使用getFromReplica方法来检索文档的一个或多个副本。

The following code would use the first replica found:

下面的代码将使用找到的第一个副本。

JsonDocument doc;
try{
    doc = bucket.get(id);
}
catch(CouchbaseException e) {
    List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
    if(!list.isEmpty()) {
        doc = list.get(0);
     }
}

Note that it is possible, when writing your application, to have write operations block until persistence and replication are complete. However the more common practice, for reasons of performance, is to have the application return from writes immediately after writing to memory of a document’s primary node, because disk writes are inherently slower than memory writes.

注意,在编写你的应用程序时,有可能让写操作阻塞,直到持久化和复制完成。然而,更常见的做法是,出于性能的考虑,让应用程序在向文档主节点的内存写入后立即从写入中返回,因为磁盘写入本身就比内存写入慢。

When using the latter approach, if a recently updated document’s primary node should fail or go offline before the updates have been fully replicated, replica reads may or may not return the latest version of the document.

当使用后一种方法时,如果最近更新的文件的主节点在更新被完全复制之前发生故障或脱机,复制的读取可能会或可能不会返回文件的最新版本。

It is also worth noting that Couchbase retrieves replicas (if any are found) asynchronously. Therefore if your bucket is configured for multiple replicas, there is no guarantee as to the order in which the SDK returns them, and you may want to loop through all the replicas found in order to ensure that your application has the latest replica version available:

同样值得注意的是,Couchbase是以异步方式检索副本的(如果有的话)。因此,如果你的桶被配置为多个副本,那么SDK返回它们的顺序是没有保证的,你可能想循环浏览所有发现的副本,以确保你的应用程序有最新的副本版本可用。

long maxCasValue = -1;
for(JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) {
    if(replica.cas() > maxCasValue) {
        doc = replica;
        maxCasValue = replica.cas();
    }
}

6. Conclusion

6.结论

We have introduced some basic usage scenarios that you will need in order to get started with the Couchbase SDK.

我们已经介绍了一些基本的使用场景,你需要这些场景才能开始使用Couchbase SDK。

Code snippets presented in this tutorial can be found in the GitHub project.

本教程中介绍的代码片段可以在GitHub项目中找到。

You can learn more about the SDK at the official Couchbase SDK developer documentation site.

您可以在官方的Couchbase SDK开发者文档网站上了解更多关于SDK的信息。