nodejs远程连接redis
时间: 2023-01-11 19:55:36 浏览: 89
在 Node.js 中使用 redis,你可以使用第三方模块 `redis`。
安装方法:
```
npm install redis
```
连接到远程 Redis 服务器的示例代码如下:
```javascript
const redis = require('redis');
const client = redis.createClient({
host: '127.0.0.1', // Redis 服务器的地址
port: 6379, // Redis 服务器的端口
password: 'password', // 如果设置了密码,则需要填写
});
client.on('connect', function() {
console.log('Redis 连接成功。');
});
client.on('error', function(err) {
console.log('Error ' + err);
});
// 在连接成功后,你就可以执行 Redis 命令了
client.set('key', 'value', redis.print);
client.get('key', function(error, result) {
if (error) {
console.log(error);
throw error;
}
console.log('GET result ->', result);
});
// 最后,别忘了关闭连接
client.quit();
```
你也可以使用其他第三方库,如 `ioredis` 来连接 Redis。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)