Skip to content

Instantly share code, notes, and snippets.

@ib84
Created October 6, 2011 08:46
Show Gist options
  • Save ib84/1266875 to your computer and use it in GitHub Desktop.
Save ib84/1266875 to your computer and use it in GitHub Desktop.
UnifiedJedisScala3 - testing scala to remove massive code duplication of previous versions
package test
import redis.clients.util.Pool
import redis.clients.jedis._
class UnifiedJedisScala3 {
val readPool: Pool[Jedis]
val masterPool: Pool[Jedis]
val currentDB: Int = 0;
val redundancySwitch: Int = 3;
val writing: Int = 0;
def get(key: Array[Byte]): Array[Byte] = {
val f: (Transaction) => Response[Array[Byte]] = _.get(key)
wrap[Array[Byte]](f, redundancySwitch, currentDB, key).get()
}
def set(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
val f: (Transaction) => Response[Array[Byte]] = _.set(key, value)
wrap[Array[Byte]](f, writing, currentDB, key).get()
}
def wrap[Array[Byte]](x: (Transaction) => Response[Array[Byte]], switcher: Int, db: Int, key: Array[Byte]*): Response[Array[Byte]] = {
var result: Response[Array[Byte]] = null
val jedis: Jedis = if (switcher > 0) readPool.getResource else masterPool.getResource
try {
key.foreach(jedis.watch(_))
val transa = jedis.multi()
transa.select(db)
result = x(transa)
transa.exec
}
catch {
case _: Exception => result = wrap[Array[Byte]](x, switcher - 1, db, key)
}
finally {
if (switcher > 0) readPool.returnResource(jedis) else masterPool.returnResource(jedis)
}
result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment