npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@roasmax/redis

v1.0.0

Published

A comprehensive Redis toolkit for TypeScript/Node.js with scenario-based abstractions

Readme

@roasmax/redis - Redis Toolkit

一个功能全面的Redis工具包,为TypeScript/Node.js提供场景化抽象。

✨ 特性

  • 🎯 场景化抽象 - 针对不同使用场景的专门管理器
  • 🔒 类型安全 - 完整的TypeScript支持和严格类型检查
  • 🚀 生产就绪 - 包含监控、安全、性能优化等企业级特性
  • 🔧 易于使用 - 简化的API,贴近业务需求
  • 🔌 可扩展 - 插件系统和中间件支持
  • 🎨 装饰器支持 - 提供@Cache、@RateLimit、@Lock等装饰器
  • 📊 监控和统计 - 内置性能监控和健康检查
  • 🛡️ 安全特性 - 数据加密、访问控制、审计日志

🚀 快速开始

安装

pnpm install @roasmax/redis
# 或
npm install @roasmax/redis
# 或
yarn add @roasmax/redis

基础使用

import { RedisToolkit } from '@roasmax/redis';

const redis = new RedisToolkit({
  host: 'localhost',
  port: 6379,
  autoSerialize: true
});

// 连接Redis
await redis.connect();

// 缓存使用
await redis.cache.set('user:123', { name: 'John', age: 30 }, { ttl: 3600 });
const user = await redis.cache.get<User>('user:123');

// 队列使用
await redis.queue.addJob('email-queue', {
  type: 'send-email',
  payload: { to: '[email protected]', subject: 'Welcome!' }
});
const job = await redis.queue.getJob('email-queue');

// 排行榜使用
await redis.leaderboard.updateScore('game-scores', 'player1', 1500);
const topPlayers = await redis.leaderboard.getTopN('game-scores', 10);

// 断开连接
await redis.disconnect();

📚 核心功能

🗄️ 缓存管理 (CacheManager)

  • 基础缓存操作 (get/set/del)
  • TTL支持和自动过期
  • 标签缓存和批量失效
  • 缓存穿透保护
  • 统计信息和性能监控

👤 会话管理 (SessionManager)

  • 用户会话创建和验证
  • 多设备会话管理
  • 自动清理过期会话
  • 会话统计和监控

📋 队列管理 (QueueManager)

  • 简单队列 (FIFO)
  • 优先级队列
  • 延迟队列
  • 作业重试和失败处理
  • 队列统计和监控

🔢 计数器管理 (CounterManager)

  • 基础计数操作
  • 分布式计数
  • 时间窗口计数
  • 滑动窗口计数

🏆 排行榜管理 (LeaderboardManager)

  • 实时排行榜
  • 时间窗口排行榜 (日/周/月)
  • 用户排名查询
  • 周围排名查询

⏱️ 限流管理 (RateLimitManager)

  • 固定窗口限流
  • 滑动窗口限流
  • 令牌桶限流
  • 分布式限流

🔒 分布式锁管理 (LockManager)

  • 简单锁
  • 可重入锁
  • 读写锁
  • 自动释放和TTL保护

📦 集合管理 (SetManager)

  • 普通集合操作
  • 有序集合操作
  • 集合运算 (并集/交集/差集)
  • 范围查询

📡 发布订阅管理 (PubSubManager)

  • 消息发布
  • 频道管理
  • 统计信息

🌸 布隆过滤器管理 (BloomFilterManager)

  • 过滤器创建和管理
  • 元素添加和检测
  • 批量操作
  • 统计信息

📊 监控管理 (MonitoringManager)

  • 性能指标收集
  • 健康检查
  • 告警系统
  • 统计报告

🔒 安全管理 (SecurityManager)

  • 数据加密存储
  • 访问控制规则
  • 审计日志
  • 权限验证

🎨 装饰器使用

@Cache 缓存装饰器

import { Cache, setCacheManager } from '@roasmax/redis/decorators';

setCacheManager(redis.cache);

class UserService {
  @Cache({
    ttl: 300,
    key: 'user:${args[0]}',
    tags: ['user']
  })
  async getUser(userId: string) {
    return await this.fetchUserFromDB(userId);
  }
}

@RateLimit 限流装饰器

import { RateLimit, setRateLimitManager } from '@roasmax/redis/decorators';

setRateLimitManager(redis.rateLimit);

class ApiController {
  @RateLimit({
    limit: 100,
    window: 3600,
    key: 'api:${args[0]}'
  })
  async handleRequest(userId: string) {
    // API处理逻辑
  }
}

@Lock 分布式锁装饰器

import { Lock, setLockManager } from '@roasmax/redis/decorators';

setLockManager(redis.lock);

class OrderService {
  @Lock({
    key: 'order:${args[0]}',
    ttl: 30
  })
  async processOrder(orderId: string) {
    // 订单处理逻辑,防止重复处理
  }
}

📊 监控和健康检查

// 健康检查
const health = await redis.healthCheck();
console.log('Redis状态:', health.status);

// 获取统计信息
const stats = await redis.getStats();
console.log('连接统计:', stats.connection);

// 缓存详细统计
const cacheStats = await redis.cache.getStats();
console.log('缓存命中率:', cacheStats.hitRate);

// 开始监控
await redis.monitoring.startMonitoring({
  metricsInterval: 60000,  // 1分钟收集一次指标
  healthCheckInterval: 30000,  // 30秒检查一次健康状态
});

📝 示例项目

查看 examples/ 目录获取更多使用示例:

  • basic-usage.ts - 基础功能演示
  • quick-test.ts - 快速功能测试
  • remote-test.ts - 远程Redis服务器测试
  • decorator-example.ts - 装饰器使用示例
  • advanced-features.ts - 高级功能演示
  • benchmark.ts - 性能基准测试

运行示例

# 快速测试
pnpm run example:quick

# 远程测试
pnpm run example:remote

# 装饰器示例
pnpm run example:decorator

# 高级功能演示
pnpm run example:advanced

# 性能基准测试
pnpm run example:benchmark

# 运行所有示例
pnpm run example:all

🔧 配置选项

const redis = new RedisToolkit({
  // Redis连接配置
  host: 'localhost',
  port: 6379,
  password: 'your-password',
  db: 0,

  // 工具包配置
  autoSerialize: true,
  keyPrefix: 'myapp:',

  // 连接池配置
  retryAttempts: 3,
  retryDelay: 1000,
  connectionTimeout: 10000,

  // 日志配置
  logger: customLogger,
});

📈 性能基准

基于本地Redis服务器的性能测试结果:

| 操作 | 吞吐量 (ops/sec) | 平均延迟 | |------|------------------|----------| | Cache Set | 2,004 | 0.50ms | | Cache Get | 967 | 1.03ms | | Counter Increment | 2,841 | 0.35ms | | Queue Add Job | 1,233 | 0.81ms | | Rate Limit Check | 3,215 | 0.31ms | | Lock Acquire/Release | 1,205 | 0.83ms | | Set Add | 2,817 | 0.35ms | | Bloom Filter Add | 482 | 2.08ms |

总体性能: 平均 1,564 ops/sec

🤝 贡献

欢迎提交Issue和Pull Request!

📄 许可证

MIT License