How to use couchbase as a fifo queue

With a Java client, how can I use couchbase to implement a thread-safe FIFO queue? Many threads may appear in the queue, and clicking on the queue. Each object in the queue is a string [].

+3
source share
1 answer

Couchbase does not have built-in functions for creating queues, but you can do it yourself.

I will explain how to do this in a short example below. That is, we have a queue with a name queue, and it will have elements with names item:<index>. To implement a queue, you need to save your values ​​with a key, for example:, <queue_name>:item:<index>where the index will be a separate key queue:index, which you need to increase when you click on the queue and decrease when it appears.

In couchbase, you can use the increase and decrease operations to implement a queue, because these operations are atomic and thread safe.

Thus, the code for your push and pop functions will look like this:

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;
}

Sorry for the code, I used java and couchbase java client for a long time. If the java client now has callbacks such as nodejs client, you can rewrite this code to use callbacks. I think it will be better.

- add ( # client, StoreMode.Add), , . push .

UPD: , , . fifo, @avsej, : 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 , .

+4

All Articles