Java Client Library (previous release)

Communicate with Couchbase Server using Java

Overview

Note: Version 1.1 is the most recent release of this SDK.  It is recommended for all deployments.

This Couchbase Client Library for Java provides a complete interface to the functionality of Couchbase through the Java programming language. For more on Couchbase Server and Java read our Getting Started guide followed by our in-depth Couchbase and Java tutorial. Java SE 6 (or higher) is recommended for running the Couchbase Client Library.

Get Started in 5 Minutes

Here is a video that demonstrates the use of the Couchbase client library:

Up and Running with Couchbase Java Client from Couchbase on Vimeo.

  1. Download the couchbase-client and spymemcached client libraries for Java.  You will also need the dependent JAR files as well, as listed in the execution instructions below. You may just download the JARS from this zip file and include them in your classpath. 
  2. Create a simple Java class to connect to your Couchbase server called Main.java. Please substitute the server IP address of the Couchbase server depending on your installtion. You can cut and paste the code below:

    import java.net.URI;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.concurrent.TimeUnit;

    import com.couchbase.client.CouchbaseClient;
    import net.spy.memcached.internal.GetFuture;
    import net.spy.memcached.internal.OperationFuture;

    public class Main {
      public static final int EXP_TIME = 10;
      public static final String KEY = "spoon";
      public static final String VALUE = "Hello World!";

      public static void main(String args[]) {
        // Set the URIs and get a client
        List<URI> uris = new LinkedList<URI>();

        Boolean do_delete = false; //

        // Connect to localhost or to the appropriate URI
        uris.add(URI.create("http://127.0.0.1:8091/pools"));

        CouchbaseClient client = null;
        try {
          client = new CouchbaseClient(uris, "default", "");
        } catch (Exception e) {
          System.err.println("Error connecting to Couchbase: "
            + e.getMessage());
          System.exit(0);
        }
        // Do a synchrononous get
        Object getObject = client.get(KEY);
        // Do an asynchronous set
        OperationFuture<Boolean> setOp = client.set(KEY, EXP_TIME, VALUE);
        // Do an asynchronous get
        GetFuture getOp = client.asyncGet(KEY);
        // Do an asynchronous delete
        OperationFuture<Boolean> delOp = null;
        if (do_delete) {
          delOp = client.delete(KEY);
        }
        // Shutdown the client
        client.shutdown(3, TimeUnit.SECONDS);
        // Now we want to see what happened with our data
        // Check to see if our set succeeded
        try {
          if (setOp.get().booleanValue()) {
            System.out.println("Set Succeeded");
          } else {
            System.err.println("Set failed: "
                + setOp.getStatus().getMessage());
          }
        } catch (Exception e) {
          System.err.println("Exception while doing set: "
              + e.getMessage());
        }
        // Print the value from synchronous get
        if (getObject != null) {
          System.out.println("Synchronous Get Suceeded: "
              + (String) getObject);
        } else {
          System.err.println("Synchronous Get failed");
        }
        // Check to see if ayncGet succeeded
        try {
          if ((getObject = getOp.get()) != null) {
            System.out.println("Asynchronous Get Succeeded: "
                + getObject);
          } else {
            System.err.println("Asynchronous Get failed: "
                + getOp.getStatus().getMessage());
          }
        } catch (Exception e) {
          System.err.println("Exception while doing Aynchronous Get: "
              + e.getMessage());
        }
        // Check to see if our delete succeeded
        if (do_delete) {
          try {
            if (delOp.get().booleanValue()) {
              System.out.println("Delete Succeeded");
            } else {
              System.err.println("Delete failed: " +
                  delOp.getStatus().getMessage());
            }
          } catch (Exception e) {
            System.err.println("Exception while doing delete: "
                + e.getMessage());
          }
        }
      }
    }
  3. Compile the application:

    javac -cp couchbase-client-1.0.2.jar:spymemcached-2.8.0.jar Main.java
  4. Run your application, including the dependencies in your Java classpath:

    java -cp .:couchbase-client-1.0.2.jar:spymemcached-2.8.0.jar:jettison-1.1.jar:netty-3.2.0.Final.jar:commons-codec-1.5.jar Main

You would substiute a ';' for a ':' in the commands above when running on a Windows system.

You should see output similar to the following:

2012-01-16 15:06:29.265 INFO com.couchbase.client.CouchbaseConnection:  Added {QA sa=/127.0.0.1:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2012-01-16 15:06:29.277 INFO com.couchbase.client.CouchbaseConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@1d3c468a
2012-01-16 15:06:29.420 INFO com.couchbase.client.CouchbaseConnection:  Shut down Couchbase client
Synchronous Get failed
Set Succeeded
Asynchronous Get Succeeded: Hello World!

The Synchronous Get failed as there was no spoon in the world. If there was an existing spoon, you should see output as below.

If you run the program a second time within 10 seconds (as specified by EXP_TIME in code above), you should see the "Hello World!" message again as there is now a spoon in the world. Consequently, the synchronous Get succeeds as well.

2012-01-16 15:37:12.242 INFO com.couchbase.client.CouchbaseConnection:  Added {QA sa=/127.0.0.1:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2012-01-16 15:37:12.253 INFO com.couchbase.client.CouchbaseConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@7f2ad19e
2012-01-16 15:37:12.439 INFO com.couchbase.client.CouchbaseConnection:  Shut down Couchbase client
Synchronous Get Succeeded: Hello World!
Set Succeeded
Asynchronous Get Succeeded: Hello World!

If you run the program a third time after 10 seconds (as specified by EXP_TIME in code above), you will notice that the Synchronous Get failed again as the TTL (Time to Live) on the key has expired. If you modify the do_delete flag to true you will notice that the Synchronous Get will fail no matter how frequently or how often you run it. You could play around by modifying these values in your code and noticing the changes.

You're done! You can now start writing and developing with Java and Couchbase server. For a more detailed overview, read the Getting Started Guide, then move on to the Couchbase and Java Tutorial.

Getting Started Guide

Get up to speed on using Java with Couchbase using our Getting Started Guide. This guide will take you through all the basic steps required to write, compile, and execute your first application. You can also download the entire guide as HTML (Zip).

Tutorial

For a deeper guide to using Java to communicate with Couchbase read our Couchbase and Java Tutorial. Using this guide you will write a simple message application using Couchbase and Java, showing you a range of techniques including using buckets and vbuckets, key/value manipulation, error handling, and the TAP API. You can also download the guide as HTML (Zip).

API Reference

The Couchbase API Reference covers the main API calls and interface for storing and retrieving data in your Couchbase Server from Java. Also available for downloading as HTML (Zip)