Get & Install Couchbase Server. Come back here when you're done.
The Java client libraries have been updated to be compatible with Couchbase Server 2.0 Developer Preview. It adds new features through the View and Query objects which enable to you to access your data with simple Javascript Map-Reduce based views.
See the server developer documentation for information on creating views and the getting started guide for information on how to use the client library.
Get the client library and its dependencies. It can either be downloaded as a zipfile or you could use Maven. This client depends on spymemcached-2.8.12, netty-3.5.5.Final, httpcore-4.1.1, httpcore-nio-4.1.1, jettison-1.1 and commons-codec-1.5. These dependencies have been bundled in the zipfile.
Now that you have installed Couchbase and have probably created a cluster of Couchbase servers, it is time to install the client libraries, couchbase-client and spymemcached, and start storing data into the clusters.
Here's a quick outline of what you'll do:
If you need to set up the server, you can do with the Couchbase Administrative Console, or Couchbase Command-Line Interface (CLI), or the Couchbase REST-API. For information and instructions, see:
You might be curious what the simplest Java program to talk to Couchbase might look like, and how you might compile and run it.
We will create a connection and we will look at some of the operations that the library supports. The asynchronous operations return a Future object. You can wait for the operation to complete and check the status of the operation.
Listing 1: Main.java
import com.couchbase.client.CouchbaseClient;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.internal.OperationFuture;
public class App {
// the unique key of the document
public static final String KEY = "beer_Wrath";
// expiration time of the document (use 0 to persist forever)
public static final int EXP_TIME = 10;
// the JSON encoded document
public static final String VALUE =
"{\"name\":\"Wrath\",\"abv\":9.0,"
+ "\"type\":\"beer\",\"brewery_id\":\"110f1a10e7\","
+ "\"updated\":\"2010-07-22 20:00:20\","
+ "\"description\":\"WRATH Belgian-style \","
+ "\"style\":\"Other Belgian-Style Ales\","
+ "\"category\":\"Belgian and French Ale\"}";
public static void main(String args[]) {
// Set the URIs and get a client
List<URI> uris = new LinkedList<URI>();
// Connect to localhost or to the appropriate URI(s)
uris.add(URI.create("http://192.168.1.101:8091/pools"));
uris.add(URI.create("http://192.168.1.102:8091/pools"));
CouchbaseClient client = null;
try {
// Use the "default" bucket with no password
client = new CouchbaseClient(uris, "default", "");
} catch (IOException e) {
System.err.println("IOException connecting to Couchbase: " + e.getMessage());
System.exit(1);
}
// Do an asynchronous set
OperationFuture<Boolean> setOp = client.set(KEY, EXP_TIME, VALUE);
// 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 (InterruptedException e) {
System.err.println("InterruptedException while doing set: " + e.getMessage());
} catch (ExecutionException e) {
System.err.println("ExecutionException while doing set: " + e.getMessage());
}
// Shutdown and wait a maximum of three seconds to finish up operations
client.shutdown(3, TimeUnit.SECONDS);
System.exit(0);
}
}
shell> javac -cp couchbase-client-1.1.6.jar:spymemcached-2.8.12.jar \
Main.java
shell> java -cp .:couchbase-client-1.1.6.jar:spymemcached-2.8.12.jar:\
jettison-1.1.jar:netty-3.5.5.Final.jar:commons-codec-1.5.jar:\
httpcore-4.1.1.jar:httpcore-nio-4.1.1.jar Main
Of course, substitute your own Couchbase server IP address. If you are on Linux or Mac OS X replace the semi-colon in the second command-line with a colon.
If you want to make your life easier, Couchbase provides a Maven repository through which you can import the Client SDK and all its dependencies very easily. The documentation on how to do this can be found in the manual here.
The program shows how to do an asynchronous set. We persist a JSON object of type beer, with a key of beer_Wrath. It does an asynchronous set operation with the set() operation as below which returns an OperationFuture object.
// 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 (InterruptedException e) {
System.err.println("InterruptedException while doing set: " + e.getMessage());
} catch (ExecutionException e) {
System.err.println("ExecutionException while doing set: " + e.getMessage());
}
As we will see here, persisting data in JSON format provides the capabilities of defining secondary indexing using query and views. There are several Java libraries that provides APIs for mapping JSON data as a Java class and vice versa. Using these libraries makes it easy to manipulate JSON data in a Java program.
In this section we will look at how to Create, Read, Update and Delete (CRUD) JSON-based documents.
These program snippets assume that Couchbase Server 2.0 is installed and the sample data which is contained in beer-sample is created and ready for use. The beer-sample data can be installed either during the initial wizard or loaded later through the Web-UI under "Settings/Sample Buckets".
public class Beer {
String name;
float abv;
float ibu;
float srm;
int upc;
String type;
String brewery_id;
String updated;
String description;
String style;
String category;
}
function (doc, meta) {
if (doc.type && doc.name && doc.type == "beer") {
emit(doc.name, meta.id);
}
}
// Init the CouchbaseClient as seen above.
// CouchbaseClient client = new CouchbaseClient(...);
// Load the View "by_name" from the design doc "beer"
View view = client.getView("beer", "by_name");
// Create a new View Query
Query query = new Query();
query.setKey("Wrath"); // Only retreive this specific key
query.setIncludeDocs(true); // Include the full document as well
// Query the Cluster and return the View Response
ViewResponse result = client.query(view, query);
// Iterate over the results and print out some info
Iterator<ViewRow> itr = result.iterator();
Gson gson = new Gson();
while(itr.hasNext()) {
ViewRow row = itr.next();
// Print out some infos about the document
System.out.println("The Key is: " + row.getKey());
System.out.println("The full document is: " + row.getDocument());
// Convert it back to an object with gson
Beer beer = gson.fromJson( (String) row.getDocument(), Beer.class);
System.out.println("Hi, my name is " + beer.name + "!");
}
beer.name = String.format("%s_MAX", beer.name);
String beerId = beer.name;
client.add(beerId, 0, gson.toJson(beer));
beer.abv = 10.0f;
client.replace(beerId, 0, gson.toJson(beer));
client.delete(beerId);