Skip to content

Instantly share code, notes, and snippets.

@dustismo
Created August 26, 2011 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustismo/1174012 to your computer and use it in GitHub Desktop.
Save dustismo/1174012 to your computer and use it in GitHub Desktop.
public class RedisQueue {
protected Log log = LogFactory.getLog(RedisQueue.class);
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
String queueName = "test";
boolean lifo = false;
//how long to keep keys around to verify uniqueness.
//default to 2 hours
int uniquenessSeconds = 60*60*2;
public void addTask(String idStr, String task) {
Jedis jedis = pool.getResource();
try {
byte[] id = this.getIdBytes(idStr);
//uniqueness check
Long t = jedis.setnx(id, "1".getBytes());
if (t == 0l) {
log.warn("dup task: " + id);
return;
}
//expire the uniqueness entry after X seconds
jedis.expire(id, this.uniquenessSeconds);
jedis.lpush(this.queueName.getBytes(), task.getBytes());
} finally {
pool.returnResource(jedis);
}
}
public String nextTask() {
Jedis jedis = pool.getResource();
try {
if (this.lifo)
return new String(jedis.lpop(this.queueName.getBytes()));
else
return new String(jedis.rpop(this.queueName.getBytes()));
} finally {
pool.returnResource(jedis);
}
}
private byte[] getIdBytes(String id) {
//do an sha1 hash on id?
return (this.queueName + ":" + id).getBytes();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment