Couchbase Java Client Library 1.1

冯奇思
2023-12-01

Step 0: Get a Server

Get & Install Couchbase Server. Come back here when you're done.

Step 1: Get a Client Library

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.

Step 2: Try it out!

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:

  • Create an Eclipse or NetBeans project and set up the Couchbase Client Libraries as referenced libraries. You'll need to include the libraries at compile time.
  • Write a simple program to demonstrate connecting to Couchbase and saving some data. Explore some of the API methods that will take you further than the simple program. 
  • Define a view and how to access it using the View and Query objects in a Java program.

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:

Hello Couchbase

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);
  }
}


 

  1. Enter the code in listing 1 into a file.
  2.  Ensure that the main executable file, all the client libraries for Java and dependencies is included in the classpath for your IDE.
  3.  Or you could type the following commands for instance:
    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.

    // Do an asynchronous set
    OperationFuture <Boolean > setOp = client. set (KEY, EXP_TIME, VALUE ) ;
    We now check status of the set() operation as below.
     
    // 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());
    }

    The program will produce the following output in addition to other informational messages.
    Set Succeeded
    Much of the output is logging statements produced by the client library, to inform you of what's going on inside the client library.  Congratulations, you've taken your first small step into a much larger world.
     

    Persisting JSON using Java

    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.

    CRUD Operations with JSON

    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".

    We will use the Google gson libraries to do this although we could have used any other JSON library for Java.
     
    We first define a Java class(Beer.java) to handle the mapping of the Beer data between Java and JSON.
     
    Listing 2: The Beer class to "model" the JSON document.
     
    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;
    }

    Working with Views

    Next define a view on the data bucket beer-sample.  The view can be defined via the Admin console on the server. Click on the Views tab and the Press the Create Development View button. Provide the name of the design document as beer and the view name as by_name and enter the map reduce code as below.
     
    function (doc, meta) {
      if (doc.type && doc.name && doc.type == "beer") {
        emit(doc.name, meta.id);
      }
    }

    The View above will look at the documents in the bucket and emit the name and id as a key value pair, if they are of type beer and they have a name. Click "Save" and then go back and click "Publish" in the "Development Views" tab, to apply the index to your entire dataset and publish it into production.
     
    The following code snippet will read a document using the view that was just created where the name of the beer is "Wrath". Using the gson libraries we instantiate a Java object of type Beer that we defined above (make sure to connect to the "beer-sample" bucket instead of the "default" one as shown in Listing 1).
     
    // 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 + "!");
    }
    

    The following code snippet will create a document where the name of the beer is "Wrath_MAX" and we will inherit the same values that we read earlier. These values can be changed, as we shall see later. We will persist the same data with a new key by updating the key and using the gson libraries to persist the data. We use the beer name and precede it with the type to make it unique. In this case,  beer_Wrath_MAX
     
    beer.name = String.format("%s_MAX", beer.name);
    String beerId = beer.name;
    client.add(beerId, 0, gson.toJson(beer));

    In the following code snippet, we will update the abv of the document and store it back as below.
     
    beer.abv = 10.0f;      
    client.replace(beerId, 0, gson.toJson(beer));

    Finally we delete the document that was just added as below.
     
    client.delete(beerId);

    As you can see, it's very straightforward to persist JSON data on the server using Java. Please refer to the tutorial for a more detailed discussion of using JSON and how to define views and queries based on the JSON data.
     
 类似资料:

相关阅读

相关文章

相关问答