The first class we're going to implement is the
ConnectionManager in the
src/main/java/com/couchbase/beersample
directory. This is a ServletContextListener
which starts the CouchbaseClient on startup and
closes the connection when the application is shut down. Here is
the full class, the discussion follows afterwards (the comments
and imports have been removed to shorten the listing a bit).
package com.couchbase.beersample; public class ConnectionManager implements ServletContextListener { private static CouchbaseClient client; private static final Logger logger = Logger.getLogger( ConnectionManager.class.getName()); @Override public void contextInitialized(ServletContextEvent sce) { logger.log(Level.INFO, "Connecting to Couchbase Cluster"); ArrayList<URI> nodes = new ArrayList<URI>(); nodes.add(URI.create("http://127.0.0.1:8091/pools")); try { client = new CouchbaseClient(nodes, "beer-sample", ""); } catch (IOException ex) { logger.log(Level.SEVERE, ex.getMessage()); } } @Override public void contextDestroyed(ServletContextEvent sce) { logger.log(Level.INFO, "Disconnecting from Couchbase Cluster"); client.shutdown(); } public static CouchbaseClient getInstance() { return client; } }
The contextInitialized and the
contextDestroyed method are called on startup
and shutdown. When the application starts, the
CouchbaseClient is initialized with the list of
nodes, the bucket name and the password (empty). Note that in a
production deployment, you want to fetch these
environment-dependent settings from a config file. The
getInstance() method will be called from the
servlets to obtain the CouchbaseClient
instance.
When you publish your application, you should see in the server logs that Couchbase is correctly connecting to the bucket. If an exception is raised during this phase, it means that your settings are wrong or you don't have no Couchbase Server running at the given nodes.
INFO: Connecting to Couchbase Cluster SEVERE: 2012-12-05 14:39:00.419 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 SEVERE: 2012-12-05 14:39:00.426 INFO com.couchbase.client.CouchbaseConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl@1b554a4 SEVERE: 2012-12-05 14:39:00.458 INFO net.spy.memcached.auth.AuthThread: Authenticated to localhost/127.0.0.1:11210 SEVERE: 2012-12-05 14:39:00.487 INFO com.couchbase.client.ViewConnection: Added localhost to connect queue SEVERE: 2012-12-05 14:39:00.489 INFO com.couchbase.client.CouchbaseClient: viewmode property isn't defined. Setting viewmode to production mode INFO: WEB0671: Loading application [com.couchbase_beersample-java_war_1.0-SNAPSHOT] at [/] INFO: com.couchbase_beersample-java_war_1.0-SNAPSHOT was successfully deployed in 760 milliseconds.