4

I was able to connect to Amazon ElastiCache (Redis) using Node.js libraries, which are redis and redis-clustr without any error. But get couldn't get slot allocation error whenever I tried to set key and value pair in Node.js app running on Amazon EC2 instance. My Amazon ElastiCache has one primary node and one replica (that is two node).

This is the code sample used for the connection:

const redis_cluster = require('redis-clustr');
const redis_client = require('redis');

let redis = new redis_cluster({
    servers: [
        {
             host: global.gConfig.redis.redis_host,
             port: global.gConfig.redis.redis_port
        }
    ],
    createClient: (port, host) => {
        return redis_client.createClient(port, host);
    }
});

// connection error
redis.on('error', err => {
    // log the error to log file
    global.gLogger.log('error', err.message, {stack: err.stack});
});

// add to global variables
global.gRedisClient = redis;

After I have established a connection to Amazon ElastiCach, the code sample below is how I retrieve values from Redis:

gRedisClient.mget(['run:123', 'walk:123'], (err, replies) => {...});

I use Redis multi() for bach operations and mget() to retrieve values at once. Am new to using Amazon ElastiCach, any help will be appreciated. Thank you.

Cocest
  • 147
  • 1
  • 2
  • 15

3 Answers3

0

I experienced the same. My reason was that my ElastiCache was configured as Master-Slave, and therefore redis-clustr is not needed. Connect to it using e.g. ioredis:

const Redis = require('ioredis');
const opts = {
    host: "your_host",
    port: 6379,
    autoResubscribe: true,
    maxRetriesPerRequest: 5
};
const redis = new Redis(opts);
Dénes Tarján
  • 576
  • 2
  • 4
  • 16
0

Just keep try ping() or other commands first until redis-clustr returns correct answer.

lk_vc
  • 1,136
  • 20
  • 26
0

The error couldn't get slot allocation can be thrown if the server is using tls but it isn't configured in the client. You can enable it with redisOptions:

let redis = new redis_cluster({
    servers: [
        {
             host: global.gConfig.redis.redis_host,
             port: global.gConfig.redis.redis_port
        }
    ],
    redisOptions: {
        tls: {} // an empty object is enough to enable it with defaults
    },
    createClient: (port, host) => {
        return redis_client.createClient(port, host);
    }
});
Mark Achée
  • 517
  • 1
  • 4
  • 14
  • Thank's for your contribution. My configuration was actually using one node, not two. I have fixed the error. – Cocest Oct 02 '20 at 06:43