Connecting to Couchbase Server

After you have your Couchbase Server up and running, and your chosen Couchbase Client libraries installed on a web server, you create the code that connects to the server from the client.

Create your first bucket

The first thing you will want to do after setting up Couchbase Server and exploring the SDKs is to create a data bucket. You can do so with the Couchbase Admin Console, or you can use the REST API. For your first application in this chapter, we will show the REST API approach, which you may be less familiar with after your initial server install.

You create either a Couchbase or memcached bucket using the REST API. When you make a request, you provide a REST request using a REST client or a UNIX utility such as curl.

  1. Make a new bucket request to the REST endpoint for buckets and provide the new bucket settings as request parameters:

    shell> curl -u Administrator:password \
    -d name=newBucket -d ramQuotaMB=100 -d authType=none \
    -d replicaNumber=1 -d proxyPort=11215 http://localhost:8091/pools/default/buckets
    						

    To create a bucket we first provide our credentials for the bucket. These are the same credentials we established when we first installed Couchbase Server. For the sake of convenience, we create a single Couchbase bucket named newBucket with a RAM quota of 100MB. We require no authentication for the bucket and set the proxy port for the bucket to 11215.

    Couchbase Server sends back this HTTP response:

    202
  2. You can check your new bucket exists and is running by making a REST request to the new bucket:

    shell> curl http://localhost:8091/pools/default/buckets/newBucket

    Couchbase Server will respond with a JSON document containing information on the new bucket:

    
    {  
       "name":"newcachebucket",
       "bucketType":"couchbase",
       ...
       "bucketCapabilities":[  
          "touch",
          "couchapi"
       ]
    }
    

    For this request we go to the same REST URI used when we created the bucket, plus we add the endpoint information for the new bucket, /newBucket. For this type of request we do not need to provide any credentials. The response document contains other REST requests you can make for the bucket as well as bucket settings/properties.

After you create your first data bucket, you can begin interacting with that bucket using a Couchbase SDK.

Connecting with Couchbase SDKs

To create a connection to Couchbase Server you create a Couchbase client instance which contains and manages connection information to the server. By default Couchbase Server uses the URI http://localhost:8091/pools for connections with Couchbase SDKs. This is the URI you can use to establish an initial connection to the cluster. A Couchbase SDK will also automatically adjust the port uses to communicate to the Couchbase Server based on any changes to cluster topology. Therefore it is not necessary to adjust your code for connecting to accommodate cluster rebalance, or to accommodate node addition or deletion.

In order to connect and perform data operations, you will need to have at least one default data bucket established, for instance one that you have made in the Couchbase Administrative Console or the REST API.

The following shows a basic steps for creating a connection:

  1. Include, import, link, or require Couchbase SDK libraries into your program files. In the example that follows, we require 'couchbase'.

  2. Provide connection information for the Couchbase cluster. Typically this includes URI, bucket ID, a password and optional parameters and can be provided as a list or string. To avoid failure to initially connect, you should provide and try at least two URL’s for two different nodes. In the following example, we provide connection information as "http://<host>:<port>/pools". In this case there is no password required.

  3. Create an instance of a Couchbase client object. In the example that follows, we create a new client instance in the client = Couchbase.connect statement.

  4. Perform any database operations for your applications, such as read, write, delete, or query.

  5. If needed, destroy the client, and therefore disconnect.

The following demonstrates this process using the Ruby SDK to connect to a default data bucket:


require 'couchbase'

client = Couchbase.connect "http://<host>:8091/pools"

begin
  client.set "hello", "Hello World!", :ttl => 10
  spoon = client.get "hello"
  puts spoon
rescue Couchbase::Error::NotFound => e
  puts "There is no record."
end

In this example, we set and retrieve data in a Ruby begin rescue end block. The code block attempts to set the value “Hello World!” for the key “spoon” with an expiration of 10 seconds. Then gets the value for the “spoon” key and outputs it. If the Couchbase client receives and error, it outputs “There is no spoon.”

Tip: Depending on the language you are using, you may need to be responsible for explicitly destroying the Couchbase client object, and thereby destroying the connection. Typically it is a best practice to try to reuse the same client instance across multiple processes and threads, rather than constantly create and destroy clients. This will provide better application performance and reduce processing times. For more information about client instance reuse and connection pooling, see Optimizing client instances and Maintaining persistent connections.

The next example in Java we demonstrate how it is safest to create at least two possible node URIs while creating an initial connection with the server. This way, if your application attempts to connect, but one node is down, the client automatically re-attempts to connect with the second node URL:


// Set up at least two URIs in case one server fails

List<URI> servers = new ArrayList<URI>();
servers.add("http://<host>:8091/pools");
servers.add("http://<host>:8091/pools");

// Create a client talking to the default bucket

CouchbaseClient cbc = new CouchbaseClient(servers, "default", "");

// Create a client talking to the default bucket

CouchbaseClient cbc = new CouchbaseClient(servers, "default", "");

System.err.println(cbc.get(“thisname") +
  " is off developing with Couchbase!");

A similar approach should be followed in any language when you attempt to connect to a Couchbase cluster. That is, you should set up an array of two or more possible nodes and then attempt to connect to at least one node in an array before performing other operations. The following demonstrates creating a connection with more than one possible URI in Ruby:

Couchbase.connect(:node_list => ['<host>:8091', '<host>:8091', 'example.net'])

After your initial connection with Couchbase Server, you will not need to reattempt server connection using an explicit list of node URLs after rebalance or node failure. After this initial connection, your Couchbase client will receive cluster information with all nodes available for connection. After rebalance and failover, if a client instance still exists, it will get updated cluster information with updated node URLs.

Authenticating a client

When you create a connection to the Couchbase Server, you are actually creating a new instance of a Couchbase client object which contains your connection information. Typically when you establish a bucket for your application, either in Couchbase Admin Console, or via a REST API call, you provide required credentials. When you connect to the bucket, provide your user name and password as parameters in your SDK call to Couchbase.connect() :


Couchbase.connect("http://<host>:8091/pools",
    :bucket => 'bucket1',
    :username => 'Administrator',
    :password => 'password')

This next example demonstrates use of credentials in PHP:

<?php
$cb = new Couchbase(”<host>:8091", "bucketname", "password", "user");
?>