Blog

Brad Wood

August 16, 2013

Spread the word


Share your thoughts

In our previous posts, we covered how to get Couchbase installed and set up your first cluster.  Then we showed you how to use Couchbase for an ORM secondary cache.  Now it’s time to showcase our Couchbase CacheBox provider that we released just a few days ago.  This is a CFML provider that uses the Java SDK for Couchbase and lets you create one or more named caches in CacheBox that connects to one or more buckets in a Couchbase cluster.  Once you connect up CacheBox, you can seamlessly also store ColdBox Platform cached events/views in Couchbase along with anything else you use the CacheBox API for.  So basically you have full Couchbase storage capabilities from ColdBox and non-ColdBox applications.  Let’s get started!

ForgeBox and Code

The CacheBox Couchbase provider does not ship with the ColdBox core, but can be found in our community repository; ForgeBox.  You can use this provider in any installation of CacheBox that is bundled with the ColdBox Platform, or in a standalone installation.  Here’s some handy links for you:

Installation

Download the latest version of the CacheBox Couchbase Provider from http://www.coldbox.org/forgebox/download/Couchbase-Provider. You will need to place the "Couchbase" folder somewhere in your application's web root, or in a location on the server that is accessible from a CF mapping. Contained in the folder are a few CFC files and a folder containing the jars used by the Couchbase Java SDK.

Configuration

Log into the Couchbase admin console which is http://localhost:8901 by default if installed on your local machine.  Create a bucket to use with your new CacheBox provider.  If you decide to use the “default” bucket, there will be no password needed.  (This is for Memcached compatibility) If you create a named bucket, you will need to create a password to secure that bucket if desired.

There are two CacheBox providers available for you to use: 1) CouchbaseProvider, 2) CouchbaseColdBoxProvider. They support the same configuration, but have different use cases.  Use the CouchbaseColdBoxProvider if you are using CacheBox inside of a ColdBox application. This provider has additional methods to support view and event caching.  Use the CouchbaseProvider if you are using the standalone version of CacheBox outside of a ColdBox application. This allows you to leverage Couchbase via CacheBox in any CFML application.

Once the CFCs and Jars are in place on your server, you’ll need to crack open your CacheBox configuration file, usually located in /config/CacheBox.cfc for a ColdBox application or if in standalone mode wherever you placed your CacheBox.cfc.  Add a new named cache to the "caches" struct in your configure method with the name you want:

component {

	function configure(){
	    // The CacheBox configuration structure DSL
	    cacheBox = {
	        
	        // Register all the custom named caches you like here
	        caches = { 
			myCouchbaseCache = {			
			}
		},
	    };
	}   

}

Then you will need to add the provider key which is the class path of the provider (Either ColdBox or non-ColdBox provider) and a properties structure that will hold all the configuration properties for the provider.  All properties are optional, but the most important ones you’ll want to look at are:

  • servers - A comma-delimited list or array of Couchbase servers in the format of "PROTOCOL://host:port". If you have more than one server, not all of them must be listed here. Default is http://localhost:8091
  • bucket - Name of the bucket to connect to.  Default is “default
  • password - Couchbase password for authentication to the bucket. Not used for "default" bucket.

 

There are a lot more configuration properties for the provider. You can visit our documentation for a full listing.

Here’s an example of what your CacheBox config could look like if you had Couchbase server running locally and had created a bucket called “ColdBoxCaches” with a password of “myPass”.

myCouchbaseCache = {
	// Customize this to the location on your server
        provider="models.providers.Couchbase.CouchbaseColdBoxProvider",
        properties = {
        	servers="localhost:8091",
        	bucket="ColdBoxCaches",
        	password="myPass"
        }
}

ColdBox Template Cache

If you want to have ColdBox's view and event caching feature use Couchbase, change out the "template" cache to use the Couchbase provider and that’s it.  ColdBox will automatically use whatever provider is named “template”.

template = {
	provider="model.providers.Couchbase.CouchbaseColdboxProvider",
	properties = {
	    objectDefaultTimeout = 15,
	    opQueueMaxBlockTime = 5000,
	    opTimeout = 5000,
	    timeoutExceptionThreshold = 5000,
	    ignoreCouchBaseTimeouts = true,				
	    bucket="default",
	    password="",
	    servers="127.0.0.1:8091"
	}
},

Usage

The standard API for using the Couchbase provider is the same as any CacheBox provider, please see the CacheBox Documentation or the CacheBox API Docs.  The first thing you must do is retrieve the named cache from CacheBox:

// standalone
myCouchbaseCache = application.cachebox.getCache( "myCouchbaseCache" );

// ColdBox
myCouchbaseCache = cachebox.getCache( "myCouchbaseCache" );
myCouchbaseCache = getColdBoxOCM( "myCouchbaseCache" );

// ColdBox/WireBox Injection
property name="myCouchbaseCache" inject="cachebox:myCouchbaseCache");

Once you have an instance of the cache provider you can use many of its functions to interact with Couchbase.  You can see the CacheBox Documentation or the CacheBox API Docs for all the different functions, but here are the most common ones:

// set with no timeouts
myCouchbaseCache.set(“myKey”, ”data”);

// get a key, result might be null, so always check it
local.result = myCouchbaseCache.get(“myKey”);

// Store recent news in cache for 15 minutes
myCouchbaseCache.set("recentNews",qryNews,15);

// Remove a specific key from cache
myCouchbaseCache.clear("recentNews");

// Set a complex object into the cache
myCouchbaseCache.set("array",['a','b','c','d','e']);

// Set a simple CFC into the cache for 30 minutes
myCouchbaseCache.set("user-#id#", myUser, 30);

// Clear all elements
myCouchbaseCache.clearAll();

// Clear by keysnippets with regular expressions
myCouchbaseCache.clearByKeySnippet(keySnippet="^user.*", regex=true);

// Get the metadata about a cached element
info = myCouchbaseCache.getCachedObjectMetadata("myUser");

// Get size
size = myCouchbaseCache.getSize();

// Verify an object is in the cache, this is expensive as it
// Retrieves the object to verify it exists
exists = myCouchbaseCache.lookup("myKey");

// Get cache stats
stats = myCouchbaseCache.getStats();

With this, you are well on your way to leveraging clustered caching in your ColdBox application.  You can check the Couchbase Administrator for the interactions and even the data as well so you can verify that the provider works.
 

Since the CacheBox API is consistent across providers, you can even have a different cache on development and only use Couchbase on production.  If your application is comprised of more than on CF server, they can all connect to a distributed Couchbase cluster and share the same application-wide cache.
 


 

The CacheBox debug panel is also a good way to check up on how many items are in your cache as well as look at them and perform actions like removing them from the cache. 

Debugging/Troubleshooting

In the unlikely event that something doesn't work the first time, here’s some debugging steps from the docs to help you figure out the issue.

  • Look in the "out" and "err" logs for information.  These are usually found in the servlet container's log directory.  For instance, if you're using Tomcat, look in Tomcat's log directory.  There are often messages logged there that never make it up to the CFML engine.
  • If Java errors are being puked out from the belly of the server, scroll to the BOTTOM of the stack trace.  A common pattern in Java is to catch an exception and rethrow a new "wrapped" exception that has the original one stored as the "cause".  The outermost exception is the first error message you see, but you have to scroll down to the "caused by..." part to get the real error.
  • If you're getting class not found errors, double check the jar files are in the correct directories and that you restarted the JVM.
  • If you are getting connection errors or Null pointer exceptions, check the spelling of your hostnames and ports and make sure Couchbase is actually running with the bucket name you specified in the config.
  • Make sure there's no conflicting versions of either of your jar files laying around on your hard drive that could also be in the classpath and interfering.
  • Once the library connects, you should see lines in the "out" log showing the servers being connected to successfully.  Open up the Couchbase web admin on one of your nodes and watch the "ops per second" graph while you hit your app.  If you see spikes in the graph every time you hit the app, then it's working!
  • If all else fails, please contact us so we can assist you with our professional open source services.

In our next post, we'll talk about our exciting new commercial Railo extension that natively integrates Couchbase right into your CFML engine for use with session/client cluster storage, query, object, template, and function caching.  Read that post here: Couchbase: Ortus Railo Extension

  

Add Your Comment

(1)

Aug 17, 2013 02:54:13 UTC

by Ken Smith

Thanks Brad! Great info.

Recent Entries

ColdBox 7.2.0 Released

ColdBox 7.2.0 Released

ColdBox, a widely used development platform for ColdFusion (CFML), has unveiled version 7.2. Packed with compelling new features, bug fixes, and enhancements, this release is designed to empower developers by boosting productivity, refining scheduled task capabilities, and enhancing the overall reliability and efficiency of application development. This article will delve into the key highlights of ColdBox 7.2 and elucidate how these advancements can positively impact developers in their daily coding endeavors.

Luis Majano
Luis Majano
November 20, 2023
Into the Box 2023 Series on CFCast

Into the Box 2023 Series on CFCast

Excitement is in the air as we unleash the highly anticipated ITB 2023 series exclusively for our valued CFCast subscribers – and the best part? It's FREE for CFCast members! Now is the perfect time if you haven't joined the CFCast community yet. Plus, we've got an incredible End-of-Year deal that's too good to miss

Maria Jose Herrera
Maria Jose Herrera
November 20, 2023
Ortus Deals are Finally Here!

Ortus Deals are Finally Here!

The much-anticipated Ortus End-of-the-Year Sale has arrived, and it's time to elevate your development experience! Whether you're a seasoned developer, a tech enthusiast, or someone on the lookout for top-notch projects, Ortus has something special in store for you. Brace yourself for incredible discounts across a wide array of products and services, including Ortus annual events, books, cutting-edge services, and more.

Maria Jose Herrera
Maria Jose Herrera
November 15, 2023