Pengantar Couchbase SDK untuk Java

1. Perkenalan

Dalam pengantar Couchbase SDK untuk Java ini, kami mendemonstrasikan cara berinteraksi dengan database dokumen Couchbase, yang mencakup konsep dasar seperti membuat lingkungan Couchbase, menghubungkan ke cluster, membuka bucket data, menggunakan operasi persistensi dasar, dan bekerja dengan dokumen. replika.

2. Ketergantungan Maven

Jika Anda menggunakan Maven, tambahkan berikut ini ke file pom.xml Anda:

 com.couchbase.client java-client 2.2.6 

3. Memulai

SDK menyediakan antarmuka CouchbaseEnvironment dan kelas implementasi DefaultCouchbaseEnvironment yang berisi setelan default untuk mengelola akses ke cluster dan bucket. Pengaturan lingkungan default dapat diganti jika perlu, seperti yang akan kita lihat di bagian 3.2.

Penting: Dokumentasi resmi Couchbase SDK memperingatkan pengguna untuk memastikan bahwa hanya satu CouchbaseEnvironment yang aktif di JVM, karena penggunaan dua atau lebih dapat mengakibatkan perilaku yang tidak dapat diprediksi.

3.1. Menghubungkan ke Cluster Dengan Lingkungan Default

Agar SDK secara otomatis membuat CouchbaseEnvironment dengan pengaturan default dan mengaitkannya dengan cluster kita, kita dapat terhubung ke cluster hanya dengan memberikan alamat IP atau nama host dari satu atau beberapa node di cluster.

Dalam contoh ini, kami terhubung ke cluster node tunggal di workstation lokal kami:

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

Untuk terhubung ke cluster multi-node, kami akan menentukan setidaknya dua node jika salah satunya tidak tersedia ketika aplikasi mencoba untuk membuat koneksi:

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

Catatan: Tidak perlu menentukan setiap node di cluster saat membuat koneksi awal. The CouchbaseEnvironment akan permintaan cluster sekali sambungan dibuat dalam rangka untuk menemukan node yang tersisa (jika ada).

3.2. Menggunakan Lingkungan Kustom

Jika aplikasi Anda memerlukan penyesuaian pengaturan apa pun yang disediakan oleh DefaultCouchbaseEnvironment , Anda dapat membuat lingkungan kustom dan kemudian menggunakan lingkungan itu saat menghubungkan ke cluster Anda.

Berikut adalah contoh yang menghubungkan ke cluster node tunggal menggunakan CouchbaseEnvironment kustom dengan waktu tunggu sambungan sepuluh detik dan batas waktu pencarian nilai kunci tiga detik:

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

Dan untuk terhubung ke cluster multi-node dengan lingkungan kustom:

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

3.3. Membuka Bucket

Setelah Anda terhubung ke cluster Couchbase, Anda dapat membuka satu atau lebih bucket.

Saat Anda pertama kali menyiapkan cluster Couchbase, paket penginstalan secara otomatis membuat bucket bernama "default" dengan sandi kosong.

Berikut salah satu cara untuk membuka bucket "default" jika memiliki sandi kosong:

Bucket bucket = cluster.openBucket();

Anda juga dapat menentukan nama keranjang saat membukanya:

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

Untuk keranjang lain dengan kata sandi kosong, Anda harus memberikan nama keranjang:

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

Untuk membuka keranjang yang memiliki kata sandi tidak kosong, Anda harus memberikan nama dan kata sandi keranjang :

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

4. Operasi Ketekunan

Di bagian ini, kami menunjukkan bagaimana melakukan operasi CRUD di Couchbase. Dalam contoh kami, kami akan bekerja dengan dokumen JSON sederhana yang mewakili seseorang, seperti dalam contoh dokumen ini:

{ "name": "John Doe", "type": "Person", "email": "[email protected]", "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.

4.1. Document IDs

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.

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

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

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.

For our examples, we will generate random UUID strings.

4.2. Inserting a Document

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

JsonObject content = JsonObject.empty() .put("name", "John Doe") .put("type", "Person") .put("email", "[email protected]") .put("homeTown", "Chicago");

Next, we create a JSONDocument object consisting of an id value and the 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:

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.

If a document with the supplied id already exists in the bucket, Couchbase throws a 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):

JsonDocument upserted = bucket.upsert(document);

4.3. Retrieving a Document

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

JsonDocument retrieved = bucket.get(id);

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

4.4. Updating or Replacing a Document

We can update an existing document using the upsert method:

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.

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:

JsonDocument replaced = bucket.replace(document);

4.5. Deleting a Document

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

JsonDocument removed = bucket.remove(document);

You may also remove by 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.

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

5. Working With Replicas

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.

5.1. Virtual Buckets and Replicas

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.

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.

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.

5.2. Retrieving a Document From a Replica

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.

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

The following code would use the first replica found:

JsonDocument doc; try{ doc = bucket.get(id); } catch(CouchbaseException e) { List 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:

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

6. Conclusion

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

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

Anda dapat mempelajari lebih lanjut tentang SDK di situs dokumentasi resmi pengembang Couchbase SDK.