Is there a blocking redis library for node.js?

2019-08-23 10:34发布

问题:

Redis is very fast. For most part on my machine it is as fast as say native Javascript statements or function calls in node.js. It is easy/painless to write regular Javascript code in node.js because no callbacks are needed. I don't see why it should not be that easy to get/set key/value data in Redis using node.js.

Assuming node.js and Redis are on the same machine, are there any npm libraries out there that allow interacting with Redis on node.js using blocking calls? I know this has to be a C/C++ library interfacing with V8.

回答1:

I suppose you want to ensure all your redis insert operations have been performed. To achieve that, you can use the MULTI commands to insert keys or perform other operations. The https://github.com/mranney/node_redis module queues up the commands pushed in multi object, and executes them accordingly.

That way you only require one callback, at the end of exec call.



回答2:

This seems like a common bear-trap for developers who are trying to get used to Node's evented programming model.

What happens is this: you run into a situation where the async/callback pattern isn't a good fit, you figure what you need is some way of doing blocking code, you ask Google/StackExchange about blocking in Node, and all you get is admonishment on how bad blocking is.

They're right - blocking, ("wait for the result of this before doing anything else"), isn't something you should try to do in Node. But what I think is more helpful is to realize that 99.9% of the time, you're not really looking for a way to do blocking, you're just looking for a way to make your app, "wait for the result of this before going on to do that," which is not exactly the same thing.

Try looking into the idea of "flow control" in Node rather than "blocking" for some design patterns that could be a clearer fit for what you're trying to do. Here's a list of libraries to check out:

https://github.com/joyent/node/wiki/modules#wiki-async-flow

I'm new to Node too, but I'm really digging Async: https://github.com/caolan/async



回答3:

Blocking code creates a MASSIVE bottleneck.

If you use blocking code your server will become INCREDIBLY slow.

Remember, node is single threaded. So any blocking code, will block node for every connected client.

Your own benchmarking shows it's fast enough for one client. Have you benchmarked it with a 1000 clients? If you try this you will see why blocking code is bad



回答4:

Whilst Redis is quick it is not instantaneous ... this is why you must use a callback if you want to continue execution ensuring your values are there.

The only way I think you could (and am not suggesting you do) achieve this use a callback with a variable that is the predicate for leaving a timer.