Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all Redis Commands Asynchronous?

I am new to Redis and Node.JS and have been attempting to use the two together. However I am a little confused by which functions I can use one after the other.

The following code appears to run synchronously, with the database growing in size:

client.dbsize(function(err, numKeys) {
  console.log("DB Size before hashes added" + numKeys);
  return numKeys;
});

for (var i = 0; i < 100; i++) {
  client.hmset(i, "username", "username", "answer", "answer");
  client.zadd('answer', i, i);
};

client.dbsize(function(err, numKeys) {
  console.log("DB Size after hashes added" + numKeys);
  return numKeys;
});

However, when I then try to query the sorted set 'answer' to return an array, this array, 'reply' is not immediately available to other redis functions outside the callback to 'zrevrangebyscore'.

client.zrevrangebyscore('answer', 100, 0, function(err, reply) {
  console.log (reply);
  return reply;
});

For example, a subsequent 'hgetall' function called on reply[1] returns undefined. Should I use all Redis functions (including the hmset and dbsize) in an asynchronous manner with callbacks/client.multi etc. or do some work effectively if used synchronously? All help gratefully received.

like image 269
thegsi Avatar asked Oct 17 '15 12:10

thegsi


People also ask

Is Redis synchronous or asynchronous?

Redis uses asynchronous replication, with asynchronous replica-to-master acknowledges of the amount of data processed. A master can have multiple replicas. Replicas are able to accept connections from other replicas.

Does Redis support async?

RedisGo-Async is a Go client for Redis, both asynchronous and synchronous modes are supported,,its API is fully compatible with redigo.

Is Redis sequential?

Redis Transactions make two important guarantees: All the commands in a transaction are serialized and executed sequentially.


1 Answers

Redis is single-threaded, so the commands on Redis are always executed sequentially. It looks like you might be using an async client for Redis, and that's where the confusion is coming from. Because you have no guarantees on network latency, if you're using an async Redis client, a later call can hit the Redis server before an earlier call and cause the issues you're running into. There's a very good explanation of why Async clients for Redis exist at all here.

All of that said, the important point in your case is that if you want your commands guaranteed to run synchronously, you have a few options:

  1. Use a pipeline in Redis to only have one back-and-forth with the server for all of your commands (probably a good idea anyway, unless you have some need to do something between commands).
  2. Use the async lib, like documented here.
  3. Use a synchronous Redis client. I don't know enough about Node.js to know how viable this is.
like image 125
Eli Avatar answered Sep 20 '22 01:09

Eli