Memcached in Grails: a quickie

Grails, programming

Two clients will be covered: XMemcached and spymemcached

Xmemcached

Add dependency

Add in BuildConfig.groovy:

dependencies {
...
compile 'com.googlecode.xmemcached:xmemcached:1.4.2'
}

Set up the bean

Add in conf/spring/resources.groovy:

beans = {
...
memcachedClient(net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean) {
servers="localhost:11211"
}
}

Usage in a service

class MyService {
static final int expiry = 30 // 30s

def memcachedClient

def perform() {
def val = memcachedClient.get('key')
if (!val) {
// cache miss
...
// put in cache
memcachedClient.set('key', expiry, val)
}
// use val
}
...
}

Spy Memcached

Add dependency

Add in BuildConfig.groovy:

dependencies {
...
compile 'net.spy:spymemcached:2.9.1'
}

Set up the bean

Add in conf/spring/resources.groovy:

beans = {
...
memcachedClient(net.spy.memcached.spring.MemcachedClientFactoryBean) {
servers="localhost:11211"
}
}

Usage in a service


class MyService {
static final int expiry = 30 // 30s

def memcachedClient

def perform() {
def val = memcachedClient.get('key')
if (!val) {
// cache miss
...
// put in cache
memcachedClient.set('key', expiry, val)
}
// use val
}
...
}

References