如何在nodejs中使用redis连接elasticache

问题描述 投票:0回答:1

我在aws中创建了一个elasticache redis集群。 现在我有端点(url + 端口)

网址看起来为“myredis.abc.xyz.cache.amazonaws.com”和端口 6379

现在我想在其中存储

Key:Value
对,就像我们存储在本机 Redis 中一样 (
redis.set, redis.get
)

如何为其编写nodejs代码,我不知道。我搜索了很多但没有找到合适的资源。

有人可以帮我吗?

我尝试了以下代码,但没有成功

    ElastiCacheClient,
    AddTagsToResourceCommand,
  } = require("@aws-sdk/client-elasticache");
  const conf = {
    host: "myredis.abc.xyz.cache.amazonaws.com",
    port: 6379,
    region: "us-east-1",
  };
  const client = new ElastiCacheClient(conf);
  const param = { manoj: "kumawat" };
  const command = new AddTagsToResourceCommand(param);
  const data = await client.send(command);
  console.log(data);
javascript node.js caching redis amazon-elasticache
1个回答
0
投票

您可以使用 Redis 模块连接到 Elasticache Redis 集群,如此代码所示

//load the redis module
const redis = require('redis');

//self invoking function to await the connection
(async () => {

//crete the client 
const client = redis.createClient({
    url: 'redis://my-demo-redis2-001.ukmr3w.0001.use1.cache.amazonaws.com:6379'
  });

//handle the error
client.on('error', err => console.log('Redis Client Error', err));

//on connect, report the connection
client.on('connect', () => console.log('Redis Client Connected'));

//connect to the redis server
await client.connect();

//set the key value pair
await client.set('key', 'value123');

//get the value for the key
const value = await client.get('key');

//log the value
console.log('value', value);

//disconnect from the redis server
await client.disconnect();


})();
© www.soinside.com 2019 - 2024. All rights reserved.