Skip to content

Instantly share code, notes, and snippets.

@ctoestreich
Created December 4, 2011 18:03
Show Gist options
  • Save ctoestreich/1430847 to your computer and use it in GitHub Desktop.
Save ctoestreich/1430847 to your computer and use it in GitHub Desktop.
Redis Json Cache
@Grapes([
@Grab('redis.clients:jedis:1.5.1'),
@GrabConfig(systemClassLoader = true)
])
import redis.clients.jedis.*
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovy.transform.EqualsAndHashCode
Jedis jedis = new Jedis("localhost")
def simpleCache = new SimpleCache()
jedis.flushAll()
assert jedis.get("one") == null
assert jedis.get("two") == null
def obj1 = createCache(new SimpleCache(name: "one"))
def obj2 = createCache(new SimpleCache(name: "two"))
assert obj1 == retrieveCache("one")
assert obj2 == retrieveCache("two")
@EqualsAndHashCode
class SimpleCache {
String name
String toString() {
return name
}
}
Object createCache(key) {
Jedis jedis = new Jedis("localhost")
println "caching item"
def json = new JsonBuilder(key)
println "\tjson ${json}"
jedis.set(key.toString(), json.toString())
return key
}
Object retrieveCache(key) {
Jedis jedis = new Jedis("localhost")
println "getting cached item"
def element = jedis.get(key.toString())
def json = new JsonSlurper().parseText(element)
println "\t${json}"
return new SimpleCache(json)
}
//this just combines the two create and retrieve together like original snippet
Object objectCache(key) {
Jedis jedis = new Jedis("localhost")
try {
def element = jedis.get(key.toString())
if(!element) {
println "caching item"
def json = new JsonBuilder(key)
println "\tjson ${json}"
jedis.set(key.toString(), json.toString())
return key
} else {
println "getting cached item"
def json = new JsonSlurper().parseText(element)
println "\t${json}"
return new SimpleCache(json)
}
} catch (e) {
e.printStackTrace()
println "no redis connection"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment