Couchbase is one of the most popular distributed, fault-tolerant, and highly performant Document-oriented as well as a key-value store. Like any other database (relational or NoSQL), Couchbase provides language-specific Client SDK to access DB and perform CRUD operations. You can also access Couchbase through the command-line tool, cbc or from the Couchbase web console.
This post will focus on some of the good practices for accessing Couchbase. I will be using Java SDK for this post; the concepts are applicable for any language though.
Initialize the Connection
All operations performed against Couchbase (cluster) is through Bucket instance. From the relational world perspective, Bucket is the database instance. And to create bucket instance, we need to have the instance of the Cluster.
The important point to be noted is that we should only create ONE connection to the Couchbase cluster and ONE connection to each bucket, and then statically reference those connections for use across the application. Reusing the connections will ensure that underlying resources are utilized to the fullest.
// connects to cluster running on localhostCluster cluster = CouchbaseCluster.create();// Connects cluster on 10.0.0.1 and if it fails then tries 10.0.0.2Custer cluster = CouchbaseCluster.create("10.0.0.1", "10.0.0.2");
// Opens the default bucketBucket bucket = cluster.openBucket();// Opens connections to demo bucketBucket bucket = cluster.openBucket("demo");// Opens connections to SECURED demo bucketBucket bucket = cluster.openBucket("demo", "p@ssword");
Tips#
It's good practice to pass at least two IP addresses in the create method. At the time of this call if the first host is down (for some reason); 2nd host will be tried. These IPs will be used only during initialization. If there is only one host and it's down, then you are out of luck and bucket instance will not be created!