mcpField
R
redis-expert

redis-expert

github.com/lammesenデータ・データベース69 回インストール
リポジトリ

redis-expert について

Bun.redisでアプリケーションを構築する開発者向けのRedis開発スキルです。データ構造、キャッシュ、メッセージング、検索、性能、Luaスクリプト、テストを扱い、bun-expertと併用できます。

主な機能

  1. 01Bun.redisの接続とコマンド案内
  2. 02データ構造とRedis Stackの解説
  3. 03キャッシュ、レート制限、ロックのパターン
  4. 04Pub/Sub、Streams、Luaスクリプト
  5. 05性能改善と統合テストの指針

活用シーン

  1. 01Bun.redisでキャッシュ層を実装
  2. 02Pub/SubやStreamsによるリアルタイム機能の構築
  3. 03Redis操作の統合テスト作成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/lammesen/skills --skill redis-expert

インストール後、Claude Code で/redis-expertを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

DATA-STRUCTURES.md
PATTERNS.md
PUBSUB-STREAMS.md
SCRIPTING.md
STACK-FEATURES.md
TESTING.md

詳細

Redis エキスパートスキル

Redis のデータ構造、キャッシュ戦略、Pub/Sub メッセージング、Streams、Lua スクリプト、Redis Stack モジュール(RedisJSON、RediSearch、Vector Search)に関する深い知識を持つ、Redis 開発のエキスパートです。Bun のネイティブ Redis クライアント(Bun.redis)を使用して、高性能なアプリケーションを構築できるよう支援します。

スキル間の連携

このスキルは bun-expert スキルと連携して動作します。Bun で Redis を使用する場合:

  • すべての Redis 操作に Bun.redis を使用します(外部パッケージは使用しません)
  • Bun のネイティブなパフォーマンス最適化を活用します
  • Redis の永続化ファイル操作には Bun.file() を使用します
  • Redis 統合テストには Bun のテストランナーを使用します

Bun.redis クライアントの基本

接続のセットアップ
// Default client (uses VALKEY_URL, REDIS_URL, or localhost:6379)
import { redis } from "bun";
await redis.set("key", "value");

// Custom client with options
import { RedisClient } from "bun";
const client = new RedisClient("redis://username:password@localhost:6379", {
  connectionTimeout: 10000,     // Connection timeout (ms)
  idleTimeout: 0,               // Idle timeout (0 = no timeout)
  autoReconnect: true,          // Auto-reconnect on disconnect
  maxRetries: 10,               // Max reconnection attempts
  enableOfflineQueue: true,     // Queue commands when disconnected
  enableAutoPipelining: true,   // Automatic command batching
  tls: true,                    // Enable TLS (or provide TLSOptions)
});
URL 形式
形式説明
redis://localhost:6379標準の接続
redis://user:pass@host:6379/0認証とデータベースを指定
rediss://host:6379TLS 接続
redis+tls://host:6379TLS 接続(代替形式)
redis+unix:///path/to/socketUnix ソケット
接続のライフサイクル
const client = new RedisClient();
await client.connect();           // Explicit connect (optional - lazy by default)
await client.duplicate();         // Create duplicate connection for Pub/Sub
client.close();                   // Close connection

// Event handlers
client.onconnect = () => console.log("Connected");
client.onclose = (error) => console.log("Disconnected:", error);

// Status
console.log(client.connected);      // boolean
console.log(client.bufferedAmount); // bytes buffered
自動パイプライン処理

パフォーマンス向上のため、コマンドは自動的にパイプライン処理されます。並行処理には Promise.all() を使用します:

const [a, b, c] = await Promise.all([
  redis.get("key1"),
  redis.get("key2"),
  redis.get("key3")
]);
生コマンドの実行

まだラッパーが用意されていないコマンドを実行する場合(ネイティブ対応コマンドは66個、send 経由では400個以上):

await redis.send("PFADD", ["hll", "value1", "value2"]);
await redis.send("LRANGE", ["mylist", "0", "-1"]);
await redis.send("SCAN", ["0", "MATCH", "user:*", "COUNT", "100"]);
エラー処理
try {
  await redis.get("key");
} catch (error) {
  if (error.code === "ERR_REDIS_CONNECTION_CLOSED") {
    // Handle connection closed
  } else if (error.code === "ERR_REDIS_AUTHENTICATION_FAILED") {
    // Handle auth failure
  } else if (error.message.includes("WRONGTYPE")) {
    // Handle type mismatch
  }
}

クイックリファレンス — ネイティブコマンド

カテゴリーコマンド
文字列set、get、getBuffer、del、exists、expire、ttl、incr、decr
ハッシュhget、hmget、hmset、hincrby、hincrbyfloat
セットsadd、srem、sismember、smembers、srandmember、spop
Pub/Subpublish、subscribe、unsubscribe

データ構造の完全なリファレンスについては、DATA-STRUCTURES.md を参照してください。


キーの命名規則

アプリケーション全体で一貫した命名を使用します:

パターン例用途
{entity}:{id}user:123シンプルなキー
{entity}:{id}:{field}user:123:settingsサブフィールド
{namespace}:{entity}:{id}app1:user:123マルチテナント
{operation}:{entity}:{id}cache:user:123操作固有
{entity}:{id}:{timestamp}session:abc:1703001234時刻ベース

クイックパターンリファレンス

キャッシュアサイドパターン
async function cached<T>(key: string, ttl: number, fetch: () => Promise<T>): Promise<T> {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const data = await fetch();
  await redis.set(key, JSON.stringify(data));
  await redis.expire(key, ttl);
  return data;
}

// Usage
const user = await cached(`user:${id}`, 3600, () => db.findUser(id));
レート制限
async function rateLimit(id: string, limit: number, window: number): Promise<boolean> {
  const key = `ratelimit:${id}`;
  const count = await redis.incr(key);
  if (count === 1) await redis.expire(key, window);
  return count <= limit;
}

// Usage
if (!await rateLimit(userId, 100, 60)) {
  throw new Error("Rate limit exceeded");
}
分散ロック
async function acquireLock(resource: string, ttlMs: number): Promise<string | null> {
  const token = crypto.randomUUID();
  const result = await redis.send("SET", [resource, token, "NX", "PX", ttlMs.toString()]);
  return result === "OK" ? token : null;
}

async function releaseLock(resource: string, token: string): Promise<boolean> {
  const script = `
    if redis.call("GET", KEYS[1]) == ARGV[1] then
      return redis.call("DEL", KEYS[1])
    end
    return 0
  `;
  const result = await redis.send("EVAL", [script, "1", resource, token]);
  return result === 1;
}

パターンの完全な一覧については、PATTERNS.md を参照してください。


パフォーマンスガイドライン

推奨事項
  1. 複数のコマンドにはパイプライン処理を使用します:Promise.all([...])
  2. アトミック操作を優先します:GET + SET より INCR
  3. 複雑なアトミック操作には Lua スクリプトを使用します
  4. メモリの肥大化を防ぐため、適切な TTL を設定します
  5. 値は小さく保ちます(理想は100KB未満、最大でも1MB未満)
  6. RedisClient の再利用を通じて接続プーリングを使用します
非推奨事項
  1. 本番環境での KEYS の使用は避けます — 代わりに SCAN を使用します
  2. 大きなオブジェクトを保存しないでください — 小さな部分に分割します
  3. メイン接続でのブロッキングコマンドは避けます — duplicate() を使用します
  4. TTL を無視しないでください — すべてのキャッシュデータに有効期限を設定します
モニタリング
// Server info
const info = await redis.send("INFO", ["memory"]);

// Memory usage
const memoryUsage = await redis.send("MEMORY", ["USAGE", "mykey"]);

// Slow log
const slowLog = await redis.send("SLOWLOG", ["GET", "10"]);

// Client list
const clients = await redis.send("CLIENT", ["LIST"]);

関連ドキュメント

ドキュメント説明
DATA-STRUCTURES.mdデータ構造の完全なリファレンス(文字列、ハッシュ、リスト、セット、ソート済みセット、Streams など)
STACK-FEATURES.mdRedis Stack モジュール(RedisJSON、RediSearch、Vector Search、TimeSeries)
PATTERNS.mdキャッシュ戦略、セッションストレージ、レート制限、分散ロック
PUBSUB-STREAMS.mdPub/Sub メッセージングとイベントソーシング向け Streams
SCRIPTING.mdLua スクリプトのパターンとスクリプト管理
TESTING.mdbun:test を使った Redis 操作のテストパターン

サブエージェント

エージェント使用する場面
redis-cacheキャッシュ戦略、キャッシュの無効化、TTL 管理を実装するとき
redis-search全文検索、ベクトル類似検索、RAG アプリケーションを実装するとき
redis-streamsイベントソーシング、メッセージキュー、リアルタイムデータパイプラインを実装するとき

このスキルが有効になる場面

このスキルは、次の場合に自動的に有効になります。

  • Bun.redis または RedisClient を使用するとき
  • キャッシュレイヤーを実装するとき
  • Pub/Sub を使用したリアルタイム機能を構築するとき
  • Streams を使用したイベント駆動型アーキテクチャを設計するとき
  • 全文検索またはベクトル検索を追加するとき
  • Redis 用の Lua スクリプトを作成するとき
  • Redis のパフォーマンスを最適化するとき

コメント