Redis - 命令
Redis - 现代命令用法
Section titled “Redis - 现代命令用法”Redis 命令是与 Redis 数据存储交互的基石。它们允许您管理数据、监控服务器和执行管理任务。虽然所有命令都遵循简单的文本协议(RESP),但您通常会通过客户端与它们交互。
Redis 命令行界面 (CLI)
Section titled “Redis 命令行界面 (CLI)”运行命令最直接的方式是使用 redis-cli,这是一个与 Redis 服务器捆绑在一起的强大终端客户端。它是开发、调试和管理必不可少的工具。
启动 CLI
Section titled “启动 CLI”要启动 redis-cli 并连接到在默认端口 (6379) 运行的本地 Redis 服务器,只需在终端中输入以下命令:
$ redis-cli127.0.0.1:6379>连接成功后,您可以发出任何 Redis 命令。一个很好的入门命令是 PING,它用于检查服务器的可用性。
127.0.0.1:6379> PINGPONG
127.0.0.1:6379> PING "Hello, Redis!""Hello, Redis!"连接远程或受保护的服务器
Section titled “连接远程或受保护的服务器”在生产环境中,Redis 几乎总是在远程服务器上运行,并受密码或更高级的安全措施保护。
现代连接语法(使用 URI)
Section titled “现代连接语法(使用 URI)”推荐的连接方法是使用 URI(统一资源标识符),它能简洁地封装所有连接细节。Redis 6 及更高版本支持此格式。
# 语法: redis://[<用户>:<密码>@]<主机>[:<端口>][/<数据库>]
# 连接到带密码的远程主机的示例$ redis-cli -u redis://:mysecretpassword@redis.example.com:6380redis.example.com:6380> PINGPONG使用单个标志(-h 用于主机,-p 用于端口,-a 用于密码)的旧语法仍然有效,但被认为不如现代方法。
超越 CLI:在应用程序中使用 Redis
Section titled “超越 CLI:在应用程序中使用 Redis”虽然 redis-cli 非常适合管理,但您的应用程序会使用 Redis 客户端库。这些库几乎适用于所有编程语言,并提供了更符合习惯的命令执行方式。
示例:Node.js 与 ioredis
Section titled “示例:Node.js 与 ioredis”以下是如何在 Node.js 应用程序中连接到 Redis 并运行一些命令的示例。
// 首先,安装库:npm install ioredis
const Redis = require('ioredis');
// 客户端可以接受连接字符串,就像 CLI 一样const redis = new Redis('redis://:mysecretpassword@redis.example.com:6380');
async function runDemo() { try { // 设置一个键 await redis.set('user:1:name', 'Alice');
// 获取键 const name = await redis.get('user:1:name'); console.log(`User's name is: ${name}`); // 输出: 用户的名字是: Alice
// 使用哈希存储更复杂的数据 await redis.hset('user:1:profile', { 'email': 'alice@example.com', 'plan': 'premium' });
const email = await redis.hget('user:1:profile', 'email'); console.log(`User's email is: ${email}`); // 输出: 用户的电子邮件是: alice@example.com
} catch (error) { console.error('Failed to connect or run command:', error); } finally { // 关闭连接 redis.quit(); }}
runDemo();这种使用专用库的现代方法是应用程序开发的标准,它带来了连接池、错误处理和类型安全(尤其是在与 TypeScript 结合使用时)等优点。