Search code examples
javaredisnio

how can redis nio client work corectlly?


I found some redis nio client.
it just put the command to a queue,
whenever there is a response, parse the response and attach the result to the first queue element.

for example :

get(K key){
  Command cmd = new GetCommand();
  queue.put(cmd);
  send(cmd);
}
//invoked while any data receive from server
onReceive(Response res){
  queue.take().setResult(parse(res));
}

The server can guarantee the response are sent back with the same sequence as the request are sent with?
Or it just because redis server use one thread to process request? Can I use this approach in other cases?


Solution

  • This will work, but you do need to be fairly careful with this sort of thing. On a single connection that sends commands in order, called from a single thread, you will get responses in order.

    If you have multiple threads accessing the same connection or use multiple connections on the same queue, matching responses to requests gets a lot more complicated.

    For the specific case of what I assume is the client you are using, I found a post that may answer your question more directly:

    Lettuce is a scalable thread-safe client built on top of the excellent netty framework. Multiple threads can share a single connection as long as they avoid blocking and transactional operations, and multiple connections are efficiently managed using NIO selectors. Internally lettuce is completely asynchronous and it exposes both synchronous and asynchronous interfaces, as well as asynchronous pub/sub callbacks.

    http://groups.google.com/group/redis-db/browse_thread/thread/fa05f025c9213ddf