@cogitator-ai/redis

中文文档
0.6.0发布于 2026/10/21MITTypeScriptES Module零依赖近 30 天下载 1.1万

Unified Redis client for Cogitator with standalone and cluster support

原始使用文档
文档目录38 节
  1. Installation
  2. Features
  3. Quick Start
  4. Standalone Mode
  5. Cluster Mode
  6. Creating Clients
  7. Factory Function
  8. From Environment Variables
  9. Configuration
  10. Standalone Configuration
  11. Cluster Configuration
  12. Configuration Options
  13. RedisClient Interface
  14. Key-Value Operations
  15. Sorted Sets
  16. Sets
  17. Pub/Sub
  18. Events
  19. Utility Methods
  20. Environment Variables
  21. Environment Examples
  22. Auto-Detection
  23. Cluster Key Routing
  24. Hash Tag Rules
  25. TLS Configuration
  26. Standalone with TLS
  27. Cluster with TLS
  28. NAT Mapping
  29. Examples
  30. Durable Workflow Stores
  31. Tool Cache
  32. Connection Pooling Pattern
  33. Caching Pattern
  34. Pub/Sub Pattern
  35. Health Check
  36. Graceful Shutdown
  37. Type Reference
  38. License

@cogitator-ai/redis

Unified Redis client for Cogitator with standalone and cluster support.

Installation

pnpm add @cogitator-ai/redis ioredis

ioredis (5.x or 6.x) is loaded when the first client is created; without it createRedisClient throws an install hint.

Used across Cogitator: the memory package's RedisAdapter builds on it, and the workflow RedisCheckpointStore, RedisRunStore, RedisApprovalStore and RedisTimerStore take a client from createRedisClient() (or a plain ioredis instance) as client. See Redis on the website.

Features

  • Unified Interface - Same API for standalone and cluster modes
  • Mode Detection - detectRedisMode() checks whether a server runs in cluster mode
  • Environment Config - Configure via environment variables
  • TLS Support - Secure connections with TLS
  • NAT Mapping - Support for cluster nodes behind NAT
  • Key Prefixing - Transparent key prefixes (including keys() lookups); use hash tags in cluster mode
  • Non-blocking Key Scans - keys() and the ioredis-style scan() use SCAN and cover every master node of a cluster
  • Tool-Cache Client - Satisfies RedisClientLike from @cogitator-ai/core, so it can back withCache({ storage: 'redis' })
  • Reconnect Strategy - Built-in capped reconnect backoff
  • Pub/Sub - Publish/subscribe with per-channel callbacks

Quick Start

Standalone Mode

import { createRedisClient } from '@cogitator-ai/redis';

const redis = await createRedisClient({
  url: 'redis://localhost:6379',
});

await redis.set('key', 'value');
const value = await redis.get('key');

await redis.quit();

Cluster Mode

import { createRedisClient } from '@cogitator-ai/redis';

const redis = await createRedisClient({
  mode: 'cluster',
  nodes: [
    { host: 'redis-1', port: 6379 },
    { host: 'redis-2', port: 6379 },
    { host: 'redis-3', port: 6379 },
  ],
  keyPrefix: '{cogitator}:',
});

await redis.set('key', 'value');

Creating Clients

Factory Function

import { createRedisClient } from '@cogitator-ai/redis';

// Standalone with URL
const client1 = await createRedisClient({
  url: 'redis://localhost:6379',
});

// Standalone with host/port
const client2 = await createRedisClient({
  host: 'localhost',
  port: 6379,
  password: 'secret',
  db: 1,
});

// Cluster mode
const client3 = await createRedisClient({
  mode: 'cluster',
  nodes: [
    { host: 'node1', port: 6379 },
    { host: 'node2', port: 6379 },
    { host: 'node3', port: 6379 },
  ],
});

From Environment Variables

import { createRedisClient, createConfigFromEnv } from '@cogitator-ai/redis';

const config = createConfigFromEnv();
const redis = await createRedisClient(config);

Configuration

Standalone Configuration

interface RedisStandaloneConfig {
  mode?: 'standalone';

  // Connection
  url?: string; // Redis URL (e.g., redis://user:password@localhost:6379/0)
  host?: string; // Host (alternative to url, overrides its host)
  port?: number; // Port (alternative to url, overrides its port)
  db?: number; // Database number (overrides the url's /db)

  // Authentication
  password?: string; // Redis password (overrides the url's password)

  // Options
  keyPrefix?: string; // Prefix for all keys
  tls?: boolean; // Enable TLS
  maxRetriesPerRequest?: number; // Max retries (default: 3)
  lazyConnect?: boolean; // Don't connect immediately (default: false)
}

Cluster Configuration

interface RedisClusterConfig {
  mode: 'cluster';
  nodes: { host: string; port: number }[];

  // Authentication
  password?: string;

  // Options
  keyPrefix?: string; // Use {hashtag}: format for cluster
  tls?: boolean;
  maxRetriesPerRequest?: number;
  lazyConnect?: boolean;

  // Cluster-specific
  scaleReads?: 'master' | 'slave' | 'all'; // Where to read from (default: 'master')
  natMap?: Record<string, { host: string; port: number }>; // NAT mapping
}

Configuration Options

OptionStandaloneClusterDescription
url✓-Redis connection URL
host✓-Redis host
port✓-Redis port
db✓-Database number
nodes-✓Cluster nodes array
password✓✓Authentication password
keyPrefix✓✓Key prefix
tls✓✓Enable TLS
maxRetriesPerRequest✓✓Max retry attempts
lazyConnect✓✓Lazy connection
scaleReads-✓Read from replicas
natMap-✓NAT address mapping

RedisClient Interface

The unified client interface works identically for both modes.

Key-Value Operations

await redis.get('key');

await redis.set('key', 'value');

await redis.setex('key', 3600, 'value');

await redis.del('key1', 'key2');

await redis.expire('key', 3600);

await redis.mget('key1', 'key2', 'key3');

const present = await redis.exists('key1', 'key2'); // how many of them exist

await redis.incr('counter');
await redis.decr('counter');

Sorted Sets

await redis.zadd('leaderboard', 100, 'player1');
await redis.zadd('leaderboard', 200, 'player2');

const top3 = await redis.zrange('leaderboard', 0, 2);
const all = await redis.zrange('leaderboard', 0, '-1'); // stop may be a string, as in ioredis

const highScores = await redis.zrangebyscore('leaderboard', 100, 500);

await redis.zrem('leaderboard', 'player1');

Sets

const members = await redis.smembers('myset');

Pub/Sub

A connection in subscriber mode cannot run regular commands, so subscribe on a duplicate(). Channel names are exact (they are not prefixed with keyPrefix); several callbacks can subscribe to the same channel and unsubscribe removes all of them.

const subscriber = redis.duplicate();

await subscriber.subscribe('channel', (channel, message) => {
  console.log(`Received on ${channel}: ${message}`);
});

await redis.publish('channel', 'hello');

await subscriber.unsubscribe('channel');

Events

redis.on('connect', () => console.log('Connected'));
redis.on('ready', () => console.log('Ready'));
redis.on('error', (err) => console.error('Error:', err));
redis.on('close', () => console.log('Closed'));
redis.on('reconnecting', () => console.log('Reconnecting...'));
redis.on('end', () => console.log('Connection ended'));

Utility Methods

await redis.ping();

const info = await redis.info();
const memoryInfo = await redis.info('memory');

// Relative to keyPrefix: with keyPrefix 'myapp:' this finds 'myapp:cache:*'
// and returns ['cache:a', ...], ready to pass to get/del
const cacheKeys = await redis.keys('cache:*');
await redis.del(...cacheKeys);

// One SCAN step at a time, with ioredis' signature; also relative to keyPrefix.
// In cluster mode the cursor walks every master node in turn.
let cursor = '0';
do {
  const [next, batch] = await redis.scan(cursor, 'MATCH', 'cache:*', 'COUNT', 100);
  for (const key of batch) console.log(key);
  cursor = next;
} while (cursor !== '0');

const sub = redis.duplicate();

await redis.quit();

Environment Variables

VariableDescription
REDIS_URLRedis connection URL
REDIS_HOSTRedis host when REDIS_URL is not set (default: localhost)
REDIS_PORTRedis port when REDIS_URL is not set (default: 6379)
REDIS_PASSWORDRedis password
REDIS_CLUSTER_NODESJSON array of cluster nodes; switches to cluster mode (a malformed value throws)
REDIS_KEY_PREFIXKey prefix (default: cogitator:, or {cogitator}: in cluster mode)

createConfigFromEnv(env?) reads process.env unless you pass another object; parseClusterNodesEnv(value) parses the cluster node list on its own.

Environment Examples

Standalone:

REDIS_URL=redis://localhost:6379
REDIS_PASSWORD=secret
REDIS_KEY_PREFIX=myapp:

Cluster:

REDIS_CLUSTER_NODES='[{"host":"10.0.0.1","port":6379},{"host":"10.0.0.2","port":6379}]'
REDIS_PASSWORD=secret
REDIS_KEY_PREFIX={myapp}:

Auto-Detection

Automatically detect if Redis is running in cluster mode:

import { createRedisClient, detectRedisMode, type RedisConfig } from '@cogitator-ai/redis';

const mode = await detectRedisMode({
  host: 'localhost',
  port: 6379,
});

console.log(`Redis mode: ${mode}`);

const config: RedisConfig =
  mode === 'cluster'
    ? { mode: 'cluster', nodes: [{ host: 'localhost', port: 6379 }] }
    : { host: 'localhost', port: 6379 };

const redis = await createRedisClient(config);

Cluster Key Routing

In cluster mode, use hash tags to ensure related keys route to the same slot:

const redis = await createRedisClient({
  mode: 'cluster',
  nodes: [{ host: 'redis-1', port: 6379 }],
  keyPrefix: '{myapp}:', // Hash tag prefix
});

// All these keys route to the same slot because of {myapp}
await redis.set('users:123', '...'); // → {myapp}:users:123
await redis.set('sessions:456', '...'); // → {myapp}:sessions:456

Hash Tag Rules

  • Use {hashtag}: format for prefixes
  • Content inside {} determines slot routing
  • Keys with same hash tag go to same node
  • Required for multi-key operations in cluster

TLS Configuration

Standalone with TLS

const redis = await createRedisClient({
  url: 'rediss://secure.redis.host:6379', // Note: rediss://
  tls: true,
});

Cluster with TLS

const redis = await createRedisClient({
  mode: 'cluster',
  nodes: [
    { host: 'secure-1.redis.host', port: 6379 },
    { host: 'secure-2.redis.host', port: 6379 },
  ],
  tls: true,
  password: 'secret',
});

NAT Mapping

For cluster nodes behind NAT/load balancer:

const redis = await createRedisClient({
  mode: 'cluster',
  nodes: [{ host: 'external.host', port: 6379 }],
  natMap: {
    '10.0.0.1:6379': { host: 'external-1.host', port: 6379 },
    '10.0.0.2:6379': { host: 'external-2.host', port: 6379 },
    '10.0.0.3:6379': { host: 'external-3.host', port: 6379 },
  },
});

Examples

Durable Workflow Stores

import { createRedisClient } from '@cogitator-ai/redis';
import { RedisRunStore, RedisCheckpointStore } from '@cogitator-ai/workflows';

const redis = await createRedisClient({ url: process.env.REDIS_URL });

const runStore = new RedisRunStore({ client: redis });
const checkpointStore = new RedisCheckpointStore({ client: redis });

Tool Cache

A RedisClient satisfies RedisClientLike from @cogitator-ai/core, so it backs Redis tool caching without ioredis-specific code. In cluster mode use a hash-tag keyPrefix: the cache storage sends multi-key commands (mget, del).

import { createRedisClient } from '@cogitator-ai/redis';
import { withCache, webSearch } from '@cogitator-ai/core';

const redis = await createRedisClient({ url: process.env.REDIS_URL, keyPrefix: 'myapp:' });

const cachedSearch = withCache(webSearch, {
  strategy: 'exact',
  ttl: '30m',
  maxSize: 1000,
  storage: 'redis',
  redisClient: redis,
});

Connection Pooling Pattern

import { createRedisClient, createConfigFromEnv } from '@cogitator-ai/redis';
import type { RedisClient } from '@cogitator-ai/redis';

let client: RedisClient | null = null;

async function getRedis(): Promise<RedisClient> {
  if (!client) {
    const config = createConfigFromEnv();
    client = await createRedisClient(config);
  }
  return client;
}

async function closeRedis(): Promise<void> {
  if (client) {
    await client.quit();
    client = null;
  }
}

Caching Pattern

import { createRedisClient } from '@cogitator-ai/redis';

const redis = await createRedisClient({
  url: 'redis://localhost:6379',
  keyPrefix: 'cache:',
});

async function getOrFetch<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl: number = 3600
): Promise<T> {
  const cached = await redis.get(key);
  if (cached) {
    return JSON.parse(cached);
  }

  const data = await fetcher();
  await redis.setex(key, ttl, JSON.stringify(data));
  return data;
}

const user = await getOrFetch('user:123', () => fetchUserFromDb(123), 600);

Pub/Sub Pattern

import { createRedisClient } from '@cogitator-ai/redis';

const redis = await createRedisClient({ url: 'redis://localhost:6379' });

const publisher = redis;
const subscriber = redis.duplicate();

interface Event {
  type: string;
  payload: unknown;
}

async function publish(event: Event): Promise<void> {
  await publisher.publish('events', JSON.stringify(event));
}

async function subscribe(handler: (event: Event) => void): Promise<void> {
  await subscriber.subscribe('events', (channel, message) => {
    const event = JSON.parse(message);
    handler(event);
  });
}

await subscribe((event) => {
  console.log('Received event:', event);
});

await publish({ type: 'user.created', payload: { id: 123 } });

Health Check

import { createRedisClient } from '@cogitator-ai/redis';

async function checkRedisHealth(): Promise<boolean> {
  const redis = await createRedisClient({
    url: 'redis://localhost:6379',
    lazyConnect: true,
  });

  try {
    const result = await redis.ping();
    return result === 'PONG';
  } catch {
    return false;
  } finally {
    await redis.quit();
  }
}

Graceful Shutdown

import { createRedisClient, createConfigFromEnv } from '@cogitator-ai/redis';

const redis = await createRedisClient(createConfigFromEnv());

process.on('SIGTERM', async () => {
  console.log('Shutting down...');
  await redis.quit();
  process.exit(0);
});

Type Reference

import type {
  RedisMode,
  RedisNodeConfig,
  RedisCommonOptions,
  RedisStandaloneConfig,
  RedisClusterConfig,
  RedisConfig,
  RedisClient,
} from '@cogitator-ai/redis';

import {
  createRedisClient,
  detectRedisMode,
  parseClusterNodesEnv,
  createConfigFromEnv,
  isClusterConfig,
} from '@cogitator-ai/redis';

License

MIT

版本与发布记录

@cogitator-ai/redis 共发布 30 个版本,首次发布于 2025/12/31;过去 12 个月发布了 30 个版本。

版本发布日期距今
0.6.0latest2026/10/2120 天前
0.5.32026/10/2021 天前
0.5.22026/10/071 个月前
0.5.12026/10/051 个月前
0.5.02026/10/041 个月前
0.4.02026/10/031 个月前

关于 @cogitator-ai/redis 的常见问题

@cogitator-ai/redis 是什么?

Unified Redis client for Cogitator with standalone and cluster support

如何安装 @cogitator-ai/redis?

在项目目录运行 npm install @cogitator-ai/redis,或使用 pnpm add / yarn add / bun add。

@cogitator-ai/redis 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cogitator-ai/redis 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cogitator-ai/redis 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cogitator-ai/redis 可以商用吗?

@cogitator-ai/redis 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cogitator-ai/redis 的下载量有多少?

根据 npm 官方下载统计,@cogitator-ai/redis 在 2026/10/11 – 2026/11/09 这 30 天内被下载 10,550 次,日均约 352 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cogitator-ai/redis 还在维护吗?

最新版本 0.6.0 发布于 2026/10/21(20 天前);至今共发布 30 个版本,其中过去 12 个月发布了 30 个;首次发布于 2025/12/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。