Skip to content

Instantly share code, notes, and snippets.

@jorgeuriarte
Created November 8, 2013 10:56
Show Gist options
  • Save jorgeuriarte/7369433 to your computer and use it in GitHub Desktop.
Save jorgeuriarte/7369433 to your computer and use it in GitHub Desktop.
Example of mixing asynchronous pipelined request to redis, and a concurrent algorithm with Java futures... Hints: - pipe.get() is *outside* the closure that defines de concurrent Task. - The real execution of the task (call: ...) will happen at "invokeAll(tareas)". - pipe.sync() has made redis results avalaible to tasks, even before they start b…
@Grab(group='redis.clients', module='jedis', version='2.1.0')
import redis.clients.jedis.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Callable
/**
*
*/
/* Performance meter... */
def chrono = [:]
def start = { name -> chrono[name] = System.currentTimeMillis() }
def stop = { name -> chrono[name] = (System.currentTimeMillis() - chrono[name]) }
def LIMIT = 100
ExecutorService executorService = null
try {
def redis = new Jedis("localhost", 6379)
def pipeCargaEjemplos = redis.pipelined()
start 'Cargar redis con ejemplos'
(1..LIMIT).each { pipeCargaEjemplos.setex("nombre:${it}", 60, "redis-${it}"); }
pipeCargaEjemplos.sync()
stop 'Cargar redis con ejemplos'
def pipe = redis.pipelined()
// Preparar tareas
start 'Creación de tareas'
def tareas = (1..LIMIT).collect { evento ->
def name = pipe.get("nombre:${evento}") // Pedimos a redis los datos "durante la creación" de tareas
return [
call: {
sleep(100)
return "eltexto - ${evento} - ${name.get()}"
}
] as Callable<String>
}
stop 'Creación de tareas'
// Ejecutar tareas
executorService = Executors.newFixedThreadPool(2)
start 'Redis Sync'
pipe.sync()
stop 'Redis Sync'
start 'Ejecucion de tareas'
def futures = executorService.invokeAll(tareas)
stop 'Ejecucion de tareas'
// Procesar resultados
futures.each { task ->
print "Resultados...${task.get()}"
}
} finally {
executorService?.shutdown()
}
println "\n\nTiempos: "
chrono.each { k, v ->
println "- ${k}: ${v}ms"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment