Created
August 26, 2011 18:09
-
-
Save dustismo/1174012 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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