使用Java客户端,我该如何使用couchbase实现FIFO队列并确保线程安全?队列中可能有多个线程在弹出和推入。队列中的每个对象都是一个字符串数组。
void push(string queue, string[] value){
int index = couchbase.increment(queue + ':index');
couchbase.set(queue + ':item:' + index, value);
}
string[] pop(string queue){
int index = couchbase.get(queue + ':index');
string[] result = couchbase.get(queue + ':item:' + index);
couchbase.decrement(queue + ':index');
return result;
}
queue:head
和 queue:tail
。 所以对于FIFO:void push(string queue, string[] value){
int index = couchbase.increment(queue + ':tail');
couchbase.set(queue + ':item:' + index, value);
}
string[] pop(string queue){
int index = couchbase.increment(queue + ':head') - 1;
string[] result = couchbase.get(queue + ':item:' + index);
return result;
}
queue:tail
和queue:head
的起始值不同而略有不同(它将是零、一或其他)。此外,您可以为计数器设置一些max
值,在达到该值后,queue:tail
和queue:head
将被重置为0(仅限于文档数量的限制)。如果您确实需要,还可以为每个文档设置expire
值。Queue<String> shoppingList = new CouchbaseQueue<String>("queueDocId", collection, String.class, QueueOptions.queueOptions());
shoppingList.add("loaf of bread");
shoppingList.add("container of milk");
shoppingList.add("stick of butter");
// What does the JSON document look like?
System.out.println(collection.get("queueDocId").contentAsArray());
//=> ["stick of butter","container of milk","loaf of bread"]
String item;
while ((item = shoppingList.poll()) != null) {
System.out.println(item);
// => loaf of bread
// => container of milk
// => stick of butter
}
// What does the JSON document look like after draining the queue?
System.out.println(collection.get("queueDocId").contentAsArray());
//=> []
的意思是:Java SDK 3.1 CouchbaseQueue 文档。
queue + ':head'
和queue + ':tail'
,在 push 操作时需要增加 tail,在 pop 操作时需要减少 head。 - avsej