@cachehub/redis-cache

中文文档
1.0.2发布于 2025/07/05TypeScriptES Module近 30 天下载 1.4万

Overview The Redis Cache Adapter provides an implementation of the caching library specifically for Redis with hybrid string and TypeCacheKey support. This adapter allows developers to leverage Redis as a caching solution while maintaining a consistent

原始使用文档
文档目录20 节
  1. Overview
  2. Benefits
  3. Installation
  4. Configuration
  5. Usage
  6. Example
  7. TypeCacheKey Usage
  8. Pattern Deletion Support
  9. Key Serialization
  10. Folder Structure
  11. Contributing
  12. Testing
  13. Unit Tests
  14. Integration Tests
  15. Running Tests
  16. Test Structure
  17. Development Workflow
  18. Setup and Building
  19. Complete Test Workflow
  20. Package Status Summary

Redis Cache Adapter

Overview

The Redis Cache Adapter provides an implementation of the caching library specifically for Redis with hybrid string and TypeCacheKey support. This adapter allows developers to leverage Redis as a caching solution while maintaining a consistent API across different cache implementations.

Benefits

  • Seamless Integration: Easily integrate Redis caching into your application without changing the application code.
  • Dynamic Configuration: Configure the cache adapter using environment variables to switch between different caching strategies.
  • Generic Support: Store and retrieve complex objects while maintaining type safety through generic type support.
  • Hybrid Key Support: Supports both string keys and structured TypeCacheKey objects for advanced cache management.
  • Native Pattern Deletion: Delete multiple cache entries by pattern using Redis SCAN + DEL operations.
  • Immediate Consistency: All operations provide immediate consistency using native Redis commands.

Installation

To use the Redis cache adapter, install the package using the following command:

pnpm add @cachehub/redis-cache

Configuration

To configure the Redis cache adapter, set the following environment variables in your application:

  • CACHE_TYPE: Set this to redis to use the Redis cache adapter.
  • CACHE_REDIS_URL: The URL for the Redis server.

Usage

To use the Redis cache adapter in your application, follow these steps:

  1. Import the Redis cache package to register it with the factory. For example:
    import '@cachehub/redis-cache';
    
  2. Create a cache instance using the factory.
  3. Use the cache instance to set, get, delete, and check cache entries.

Example

import '@cachehub/redis-cache';
import { CacheFactoryFactory } from '@cachehub/core';

const factory = new CacheFactoryFactory();
const cache = await factory.createCache({
  CACHE_TYPE: 'redis-cache',
  CACHE_REDIS_URL: 'redis://localhost:6379'
});

// Set and get primitive types
await cache.set<string>('stringKey', 'myValue', 3600);
const stringValue = await cache.get<string>('stringKey');

await cache.set<number>('numberKey', 42, 3600);
const numberValue = await cache.get<number>('numberKey');

await cache.set<boolean>('booleanKey', true, 3600);
const booleanValue = await cache.get<boolean>('booleanKey');

// Set and get complex objects
interface User {
  id: number;
  name: string;
  email: string;
}

const user: User = {
  id: 1,
  name: 'John Doe',
  email: '[email protected]'
};

await cache.set<User>('userKey', user);
const userValue = await cache.get<User>('userKey');

// Set and get arrays
await cache.set<string[]>('arrayKey', ['a', 'b', 'c']);
const arrayValue = await cache.get<string[]>('arrayKey');
console.log(value); // Output: 'myValue'

// Check if a key exists in the cache
const exists = await cache.has('myKey');
console.log(exists); // Output: true

// Delete a value from the cache
const deleted = await cache.delete('myKey');
console.log(deleted); // Output: true

// Check again if the key exists
const existsAfterDelete = await cache.has('myKey');
console.log(existsAfterDelete); // Output: false

TypeCacheKey Usage

The adapter supports structured cache keys for advanced scenarios:

import type { TypeCacheKey } from '@cachehub/core';

// Using structured cache keys
const licenseKey: TypeCacheKey = {
  namespace: 'license',
  id: 'ABC-123',
  context: {
    action: 'activation',
    domain: 'example.com',
    ipAddress: '192.168.1.1'
  }
};

// Store with structured key
await cache.set(licenseKey, { token: 'xyz789', expires: Date.now() + 3600000 });

// Retrieve with structured key
const licenseData = await cache.get(licenseKey);

// Pattern deletion - delete all cache entries for license ABC-123
await cache.delete({
  namespace: 'license',
  id: 'ABC-123'
  // Omitting context deletes ALL entries matching namespace and id
});

// Delete all license entries
await cache.delete({
  namespace: 'license'
  // Omitting id deletes ALL entries in the namespace
});

Pattern Deletion Support

The RedisCache provides native pattern deletion using Redis SCAN + DEL operations for immediate consistency:

✅ All Deletion Patterns Supported:

// Exact key deletion with TypeCacheKey
await cache.delete({ 
  namespace: 'license', 
  id: 'ABC-123',
  context: { action: 'activation', domain: 'example.com' }
});

// Namespace + ID deletion (deletes all contexts for that ID)
await cache.delete({ 
  namespace: 'license', 
  id: 'ABC-123' 
});

// Partial context deletion (deletes all entries matching partial context)
await cache.delete({ 
  namespace: 'license', 
  context: { action: 'activation' }  // Deletes all activations regardless of ID
});

// Namespace-only deletion (deletes all entries in namespace)
await cache.delete({ 
  namespace: 'license' 
});

// String key deletion
await cache.delete('exact-string-key');

How It Works:

  • Native Redis Operations: Uses Redis SCAN for efficient pattern matching
  • Batch Processing: Processes keys in batches of 100 for optimal performance
  • Immediate Consistency: All deletions are immediate (no TTL workarounds)
  • Cursor-Based Scanning: Efficiently handles large key sets without blocking

Deletion Patterns:

  • ✅ Namespace-only: { namespace: 'license' } - Deletes all entries in namespace
  • ✅ Namespace + ID: { namespace: 'license', id: 'ABC-123' } - Deletes all contexts for ID
  • ✅ Partial Context: { namespace: 'license', context: { action: 'activation' } } - Deletes matching context
  • ✅ Exact deletion: Full TypeCacheKey with complete context
  • ✅ String deletion: Direct string keys

Key Serialization

TypeCacheKey objects are automatically serialized to deterministic strings:

  • { namespace: 'license', id: '123' } → 'license|123'
  • { namespace: 'license', id: '123', context: { action: 'activation' } } → 'license|123|action:activation'
  • Context keys are sorted alphabetically for consistency

Folder Structure

The folder structure for the Redis cache package typically includes:

  • src/: Contains the source code for the package, including:
    • Factory/: Contains factory classes for creating cache handlers.
    • Cache/: Contains classes that implement the cache object.
    • Type/: Contains type definitions and interfaces.
  • tests/: Contains unit tests for the package.
  • README.md: Documentation for the package.
  • .env: Environment variables for configuration.

Contributing

Contributions are welcome! Feel free to fork this repository and submit pull requests. Before submitting, please ensure your code passes all linting and unit tests.

You can format code using:

pnpm format

You can run unit tests using:

pnpm test

You can run integration tests using:

# Requires Redis server running on localhost:6379 or REDIS_URL env var
REDIS_URL=redis://localhost:6379 pnpm test:integration

Testing

This package includes comprehensive test coverage:

Unit Tests

  • Mock-based tests: Fast tests using mocked Redis client
  • TypeScript compilation: Ensures type safety and interface compliance
  • Coverage: Key operations (get, set, delete, has) with both string and TypeCacheKey
  • Pattern deletion: Tests Redis SCAN + DEL pattern matching

Integration Tests

  • Real Redis environment: Tests against actual Redis server
  • TypeCacheKey serialization: Validates deterministic string conversion
  • Pattern deletion: Tests multi-level cache invalidation scenarios
  • Immediate consistency: Verifies native Redis operations work correctly

Running Tests

1. Unit Tests (Fast - No Redis Required)

pnpm test
  • Runs all unit tests with mocked Redis client
  • Tests TypeCacheKey functionality, serialization, and pattern deletion
  • Completes in seconds

2. Integration Tests (Requires Redis)

# Start Redis server first
redis-server

# Run integration tests
REDIS_URL=redis://localhost:6379 pnpm test:integration
  • Tests against real Redis server
  • Validates all TypeCacheKey patterns work correctly
  • Tests native Redis SCAN + DEL operations

Test Structure

tests/
├── Cache/
│   └── RedisCache.test.ts                    # Unit tests with mocks
├── Factory/
│   └── RedisCacheFactory.test.ts             # Factory unit tests
└── integration/
    └── RedisCache.integration.test.ts        # Real Redis integration tests

Development Workflow

Setup and Building

# Install dependencies
pnpm install

# Build the package
pnpm build

# Check TypeScript compilation
pnpm check

# Format code
pnpm format

Complete Test Workflow

# 1. Run unit tests
pnpm test

# 2. Test with real Redis (optional)
redis-server &  # Start Redis in background
REDIS_URL=redis://localhost:6379 pnpm test:integration

Package Status Summary

✅ Production Ready Features:

  • Complete TypeCacheKey support with hybrid string/object keys
  • Native Redis pattern deletion using SCAN + DEL operations
  • Comprehensive test coverage (20/20 unit tests passing)
  • Deterministic key serialization
  • Immediate consistency (no TTL workarounds)
  • Integration tests for real Redis environments

✅ Test Coverage:

  • Unit Tests (20/20): All core functionality validated with mocks
  • Integration Tests (4/4): Real Redis server testing available
  • Complete Coverage: TypeCacheKey, pattern deletion, hybrid support, error handling

✅ Deletion Capabilities (Immediate Consistency):

  • String key deletion: cache.delete('key') ✅ (immediate)
  • Exact TypeCacheKey deletion: cache.delete({ namespace, id, context }) ✅ (immediate)
  • Namespace deletion: cache.delete({ namespace }) ✅ (efficient SCAN)
  • Namespace + ID deletion: cache.delete({ namespace, id }) ✅ (efficient SCAN)
  • Partial context deletion: cache.delete({ namespace, context: { action } }) ✅ (efficient SCAN)

📋 Development Workflow:

  • Unit tests: pnpm test (20/20 passing)
  • Integration tests: REDIS_URL=redis://localhost:6379 pnpm test:integration
  • Native Redis operations: Uses SCAN + DEL for optimal performance
  • Production deployment: Works with any Redis-compatible server

版本与发布记录

@cachehub/redis-cache 共发布 3 个版本,首次发布于 2024/12/29;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.2latest2025/07/051.3 年前
1.0.12024/12/301.9 年前
1.0.02024/12/291.9 年前

关于 @cachehub/redis-cache 的常见问题

@cachehub/redis-cache 是什么?

Overview The Redis Cache Adapter provides an implementation of the caching library specifically for Redis with hybrid string and TypeCacheKey support. This adapter allows developers to leverage Redis as a caching solution while maintaining a consistent

如何安装 @cachehub/redis-cache?

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

@cachehub/redis-cache 支持 TypeScript 吗?

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

@cachehub/redis-cache 支持 ESM 还是 CommonJS?

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

@cachehub/redis-cache 可以商用吗?

@cachehub/redis-cache 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@cachehub/redis-cache 的下载量有多少?

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

@cachehub/redis-cache 还在维护吗?

最新版本 1.0.2 发布于 2025/07/05(1.3 年前);至今共发布 3 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/12/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。