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.
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.
RedisGo-Async is a Go client for Redis, both asynchronous and synchronous modes are supported,,its API is fully compatible with redigo.
Redis Transactions make two important guarantees: All the commands in a transaction are serialized and executed sequentially.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With