Redis Connection via socket on Node.js

2019-07-04 12:06发布

问题:

Because of shared hosting, my redis server on the target host does not run on a port, but on a very specific socket, which can be connected to via the socket file, only accessible to my user.

However, I have not found how I can specify connection via a socket in the node_redis and connect-redis packages, the ones I want to use.

Anyone know how to do it?

回答1:

Update: My answer below is not really correct. It turns out that the solution in the issue I mention below actually still works. It's more of a coincidence, IMO, but you can do something like this, and it should work:

var redis = require('redis'),
    client = redis.createClient('/tmp/redis.sock');

As you see from the code snippet below, this will get passed to net.createConnection which will connect to the unix socket /tmp/redis.sock.

Old answer:

There is a closed issue about this node_redis/issues/204. It seems, thought, that the underlying node.js net.createConnection API has since changed. It looks as though it would be a quite small fix in node_redis' exports.createClient function:

exports.createClient = function (port_arg, host_arg, options) {
    var port = port_arg || default_port,
        host = host_arg || default_host,
        redis_client, net_client;

    net_client = net.createConnection(port, host);

    redis_client = new RedisClient(net_client, options);

    redis_client.port = port;
    redis_client.host = host;

    return redis_client;
};

It seems as though net.createConnection will attempt to connect to a unix socket if it's called with one argument, that looks like a path. I suggest you implement a fix and send a pull request, since this seems like something worth supporting.



回答2:

There is no longer a connect string...

var client = redis.createClient(9000); // Open a port on localhost
var client = redis.createClient('/tmp/redis.sock'); // Open a unix socket
var client = redis.createClient(9000, 'example.com'); 

This, and options are documented on the README.