redis-js

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Upstash Redis SDK - Complete Skills Guide

Upstash Redis SDK 完整技能指南

This directory contains comprehensive guides for using the
@upstash/redis
SDK. These skill files are designed to help developers and AI assistants understand and use the SDK effectively.
本目录包含使用
@upstash/redis
SDK的全面指南。这些技能文件旨在帮助开发者和AI助手高效理解并使用该SDK。

Installation

安装

bash
npm install @upstash/redis
bash
npm install @upstash/redis

Quick Start

快速开始

Basic Initialization

基础初始化

typescript
import { Redis } from "@upstash/redis";

// Initialize with explicit credentials
const redis = new Redis({
  url: "UPSTASH_REDIS_REST_URL",
  token: "UPSTASH_REDIS_REST_TOKEN",
});

// Or initialize from environment variables
const redis = Redis.fromEnv();
typescript
import { Redis } from "@upstash/redis";

// 使用显式凭证初始化
const redis = new Redis({
  url: "UPSTASH_REDIS_REST_URL",
  token: "UPSTASH_REDIS_REST_TOKEN",
});

// 或从环境变量初始化
const redis = Redis.fromEnv();

Environment Variables

环境变量

Set these in your
.env
file:
bash
UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token-here
.env
文件中设置以下变量:
bash
UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token-here

Skill Files Overview

技能文件概览

Data Structures (skills/data-structures/)

数据结构(skills/data-structures/)

Redis data types with auto-serialization examples:
  • strings.md - GET, SET, INCR, DECR, APPEND with automatic type handling
  • hashes.md - HSET, HGET, HMGET with object serialization
  • lists.md - LPUSH, RPUSH, LRANGE with array handling
  • sets.md - SADD, SMEMBERS, set operations
  • sorted-sets.md - ZADD, ZRANGE, ZRANK, leaderboard patterns
  • json.md - JSON.SET, JSON.GET, JSONPath queries for nested objects
  • streams.md - XADD, XREAD, XGROUP, consumer groups
带自动序列化示例的Redis数据类型:
  • strings.md - GET、SET、INCR、DECR、APPEND操作及自动类型处理
  • hashes.md - HSET、HGET、HMGET操作及对象序列化
  • lists.md - LPUSH、RPUSH、LRANGE操作及数组处理
  • sets.md - SADD、SMEMBERS操作及集合运算
  • sorted-sets.md - ZADD、ZRANGE、ZRANK操作及排行榜模式
  • json.md - JSON.SET、JSON.GET操作及JSONPath嵌套对象查询
  • streams.md - XADD、XREAD、XGROUP操作及消费者组

Advanced Features (skills/advanced-features/)

高级功能(skills/advanced-features/)

Complex operations and optimizations:
  • auto-pipeline.md - Automatic request batching, performance optimization
  • pipeline-and-transactions.md - Manual pipelines, MULTI/EXEC, WATCH for atomic operations
  • scripting.md - Lua scripts, EVAL, EVALSHA for server-side logic
复杂操作与优化:
  • auto-pipeline.md - 自动请求批处理、性能优化
  • pipeline-and-transactions.md - 手动流水线、MULTI/EXEC、WATCH原子操作
  • scripting.md - Lua脚本、EVAL、EVALSHA服务端逻辑

Patterns (skills/patterns/)

模式(skills/patterns/)

Common use cases and architectural patterns:
  • caching.md - Cache-aside, write-through, TTL strategies
  • rate-limiting.md - Integration with @upstash/ratelimit package
  • session-management.md - Session storage and user state management
  • distributed-locks.md - Lock implementations, deadlock prevention
  • leaderboard.md - Sorted set leaderboards, real-time rankings
常见用例与架构模式:
  • caching.md - 缓存旁路、写穿透、TTL策略
  • rate-limiting.md - 与@upstash/ratelimit包集成
  • session-management.md - 会话存储与用户状态管理
  • distributed-locks.md - 锁实现、死锁预防
  • leaderboard.md - 有序集合排行榜、实时排名

Performance (skills/performance/)

性能(skills/performance/)

Optimization techniques and best practices:
  • batching-operations.md - MGET, MSET, batch operations
  • pipeline-optimization.md - When to use pipelines, performance tips
  • ttl-expiration.md - Key expiration strategies, memory management
  • data-serialization.md - Deep dive into auto serialization, custom serializers, edge cases
  • error-handling.md - Error types, retry strategies, timeout handling, debugging tips
  • redis-replicas.md - Global database setup, read replicas, read-your-writes consistency
优化技巧与最佳实践:
  • batching-operations.md - MGET、MSET、批量操作
  • pipeline-optimization.md - 流水线使用场景、性能技巧
  • ttl-expiration.md - 键过期策略、内存管理
  • data-serialization.md - 自动序列化深入解析、自定义序列化器、边缘情况
  • error-handling.md - 错误类型、重试策略、超时处理、调试技巧
  • redis-replicas.md - 全局数据库设置、只读副本、读写一致性

Migrations (skills/migrations/)

迁移(skills/migrations/)

Migration guides from other libraries:
  • from-ioredis.md - Migration from ioredis, key differences, serialization changes
  • from-redis-node.md - Migration from node-redis, API differences
从其他库迁移的指南:
  • from-ioredis.md - 从ioredis迁移、核心差异、序列化变更
  • from-redis-node.md - 从node-redis迁移、API差异

Common Mistakes (Especially for LLMs)

常见错误(尤其针对大语言模型)

❌ Mistake 1: Treating Everything as Strings

❌ 错误1:将所有内容视为字符串

typescript
// ❌ WRONG - Don't do this with @upstash/redis
await redis.set("count", "42"); // Stored as string "42"
const count = await redis.get("count");
const incremented = parseInt(count) + 1; // Manual parsing needed

// ✅ CORRECT - Let the SDK handle it
await redis.set("count", 42); // Stored as number
const count = await redis.get("count");
const incremented = count + 1; // Just use it
typescript
// ❌ 错误 - @upstash/redis不建议这么做
await redis.set("count", "42"); // 存储为字符串"42"
const count = await redis.get("count");
const incremented = parseInt(count) + 1; // 需要手动解析

// ✅ 正确 - 让SDK处理类型
await redis.set("count", 42); // 存储为数字
const count = await redis.get("count");
const incremented = count + 1; // 直接使用即可

❌ Mistake 2: Manual JSON Serialization

❌ 错误2:手动JSON序列化

typescript
// ❌ WRONG - Unnecessary with @upstash/redis
await redis.set("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(await redis.get("user"));

// ✅ CORRECT - Automatic handling
await redis.set("user", { name: "Alice" });
const user = await redis.get("user");
typescript
// ❌ 错误 - @upstash/redis无需这么做
await redis.set("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(await redis.get("user"));

// ✅ 正确 - 自动处理
await redis.set("user", { name: "Alice" });
const user = await redis.get("user");

Quick Command Reference

快速命令参考

typescript
// Strings
await redis.set("key", "value");
await redis.get("key");
await redis.incr("counter");
await redis.decr("counter");

// Hashes
await redis.hset("user:1", { name: "Alice", age: 30 });
await redis.hget("user:1", "name");
await redis.hgetall("user:1");

// Lists
await redis.lpush("tasks", "task1", "task2");
await redis.rpush("tasks", "task3");
await redis.lrange("tasks", 0, -1);

// Sets
await redis.sadd("tags", "javascript", "redis");
await redis.smembers("tags");

// Sorted Sets
await redis.zadd("leaderboard", { score: 100, member: "player1" });
await redis.zrange("leaderboard", 0, -1);

// JSON
await redis.json.set("user:1", "$", { name: "Alice", address: { city: "NYC" } });
await redis.json.get("user:1");

// Expiration
await redis.setex("session", 3600, { userId: "123" });
await redis.expire("key", 60);
await redis.ttl("key");
typescript
// 字符串
await redis.set("key", "value");
await redis.get("key");
await redis.incr("counter");
await redis.decr("counter");

// 哈希
await redis.hset("user:1", { name: "Alice", age: 30 });
await redis.hget("user:1", "name");
await redis.hgetall("user:1");

// 列表
await redis.lpush("tasks", "task1", "task2");
await redis.rpush("tasks", "task3");
await redis.lrange("tasks", 0, -1);

// 集合
await redis.sadd("tags", "javascript", "redis");
await redis.smembers("tags");

// 有序集合
await redis.zadd("leaderboard", { score: 100, member: "player1" });
await redis.zrange("leaderboard", 0, -1);

// JSON
await redis.json.set("user:1", "$", { name: "Alice", address: { city: "NYC" } });
await redis.json.get("user:1");

// 过期
await redis.setex("session", 3600, { userId: "123" });
await redis.expire("key", 60);
await redis.ttl("key");

Best Practices

最佳实践

  1. Use environment variables for credentials, never hardcode
  2. Leverage auto-serialization - pass native JavaScript types
  3. Use TypeScript types for better type safety
  4. Set appropriate TTLs to manage memory
  5. Use pipelines for multiple operations
  6. Namespace your keys (e.g.,
    user:123
    ,
    session:abc
    )
  1. 使用环境变量存储凭证,切勿硬编码
  2. 利用自动序列化 - 传入原生JavaScript类型
  3. 使用TypeScript类型提升类型安全性
  4. 设置合适的TTL管理内存
  5. 使用流水线处理多个操作
  6. 为键添加命名空间(例如:
    user:123
    session:abc

Resources

资源

Getting Help

获取帮助

For detailed information on specific topics, refer to the individual skill files in the
skills/
directory. Each file contains comprehensive examples, use cases, and best practices for its topic.
如需特定主题的详细信息,请参考
skills/
目录下的单个技能文件。每个文件都包含该主题的全面示例、用例及最佳实践。