如何使用node.js连接ElastiCache集群

23
3个回答

34

分享代码,方便后来者查看:

var RedisClustr = require('redis-clustr');
var RedisClient = require('redis');
var config = require("./config.json");

var redis = new RedisClustr({
    servers: [
        {
            host: config.redisClusterHost,
            port: config.redisClusterPort
        }
    ],
    createClient: function (port, host) {
        // this is the default behaviour
        return RedisClient.createClient(port, host);
    }
});

//connect to redis
redis.on("connect", function () {
  console.log("connected");
});

//check the functioning
redis.set("framework", "AngularJS", function (err, reply) {
  console.log("redis.set " , reply);
});

redis.get("framework", function (err, reply) {
  console.log("redis.get ", reply);
});

1
谢谢分享,但对我没有用。你使用了什么样的Elasticache Redis配置? - Ultrablendz
1
感谢您更新链接,但是在启用了集群模式的AWS Elastiredis上它无法工作。我也尝试从lambda实例而不是ec2实例中运行它,虽然这应该没有关系。 - Ultrablendz
@ZameerAnsari 我提供的是正确的主机和端口。在这种情况下可能出了什么问题? - Avani Khabiya
我添加了这段代码,它在我的电脑上运行良好,但是在使用elasticache集群模式时出现了错误。有些情况下,由于Redis重定向节点,网站会返回404页面。 - tomnyson
@tomnyson,我已经不再参与这个项目了,所以我不确定如何修复它。你能否请你找出解决方案并更新这个答案? - Zameer Ansari
显示剩余6条评论

1
您可以尝试使用ioredis进行连接。

var Redis = require('ioredis');
var config = require("./config.json");

const redis = new Redis({
  host: config.host,
  port: config.port,
  password: config.password, // If you have any.
  tls: {}, // Add this empty tls field.
});

redis.on('connect', () => {
  console.log('Redis client is initiating a connection to the server.');
});

redis.on('ready', () => {
  console.log('Redis client successfully initiated connection to the server.');
});

redis.on('reconnecting', () => {
  console.log('Redis client is trying to reconnect to the server...');
});

redis.on('error', (err) => console.log('Redis Client Error', err));

//check the functioning
redis.set("framework", "AngularJS", function(err, reply) {
  console.log("redis.set ", reply);
});

redis.get("framework", function(err, reply) {
  console.log("redis.get ", reply);
});


1
const redisClient = process.env.NODE_ENV === 'production'
  ? new Redis.Cluster(
    [
      {
        host: 'node-production-0001-001.b2tyw0.0001.use2.cache.amazonaws.com',
        port: 6379,
        flags: 'master'
      },
      {
        host: 'node-production-0001-002.b2tyw0.0001.use2.cache.amazonaws.com',
        port: 6379,
        flags: 'slave'
      },
      {
        host: 'node-production-0001-003.b2tyw0.0001.use2.cache.amazonaws.com',
        port: 6379,
        flags: 'slave'
      },
    ], {
      scaleReads: 'slave'
    }
  )
  : new Redis({
    host: process.env.REDIS_HOST || 'localhost',
    port: process.env.REDIS_PORT || 6379,
  });

启用集群模式后,这对我有用。


你导入了哪个 npm 包?我已经导入了 "redis" 包。我遇到了错误:TypeError: Redis.Cluster 不是一个构造函数。 - Sudhanshu sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接