@agendajs/redis-backend

中文文档
3.0.8发布于 2026/10/31MITTypeScriptES Module构建来源已验证近 30 天下载 6320

Redis backend for Agenda job scheduler with Pub/Sub notification support

原始使用文档
文档目录18 节
  1. Features
  2. Installation
  3. Usage
  4. Basic Usage
  5. Configuration Options
  6. Using an Existing Redis Client
  7. How It Works
  8. Storage
  9. Real-Time Notifications
  10. Distributed Locking
  11. Job Logging
  12. Automatic Usage
  13. Standalone Usage
  14. Persistence
  15. Testing
  16. Available Scripts
  17. Requirements
  18. License

@agendajs/redis-backend

Redis backend for Agenda job scheduler with Pub/Sub support for real-time job processing.

Features

  • Full Redis storage backend for Agenda jobs
  • Real-time job notifications using Redis Pub/Sub
  • Efficient job indexing with sorted sets
  • Atomic job locking with WATCH/MULTI/EXEC
  • Connection pooling via ioredis library
  • TypeScript support with full type definitions

Installation

npm install @agendajs/redis-backend
# or
pnpm add @agendajs/redis-backend
# or
yarn add @agendajs/redis-backend

Usage

Basic Usage

import { Agenda } from 'agenda';
import { RedisBackend } from '@agendajs/redis-backend';

// Create agenda with Redis backend
const agenda = new Agenda({
  backend: new RedisBackend({
    connectionString: 'redis://localhost:6379'
  })
});

// Define jobs
agenda.define('send-email', async (job) => {
  const { to, subject, body } = job.attrs.data;
  await sendEmail(to, subject, body);
});

// Start processing
await agenda.start();

// Schedule jobs
await agenda.every('5 minutes', 'send-email', { to: '[email protected]', subject: 'Hello', body: 'World' });
await agenda.schedule('in 10 minutes', 'send-email', { to: '[email protected]', subject: 'Hi', body: 'There' });

Configuration Options

import { RedisBackend } from '@agendajs/redis-backend';

const backend = new RedisBackend({
  // Redis connection string (required unless redis/redisOptions is provided)
  connectionString: 'redis://localhost:6379',

  // Or use Redis client options (creates a new client)
  redisOptions: {
    host: 'localhost',
    port: 6379,
    password: 'secret',
    db: 0
  },

  // Key prefix for all Redis keys (default: 'agenda:')
  keyPrefix: 'agenda:',

  // Channel name for Pub/Sub notifications (default: 'agenda:notifications')
  channelName: 'agenda:notifications',

  // Name to identify this Agenda instance (stored as lastModifiedBy)
  name: 'worker-1',

  // Sort order for job queries
  sort: {
    nextRunAt: 'asc',
    priority: 'desc'
  }
});

Using an Existing Redis Client

If your application already has a Redis client, you can pass it directly. The client will not be closed when Agenda disconnects:

import { Redis } from 'ioredis';
import { RedisBackend } from '@agendajs/redis-backend';

// Your app's existing Redis client
const redis = new Redis('redis://localhost:6379');

const backend = new RedisBackend({ redis });

// After agenda.stop(), your Redis client is still usable

How It Works

Storage

The backend stores jobs using Redis data structures:

  • Hashes ({prefix}job:{id}) - Store job data as key-value pairs
  • Sets ({prefix}jobs:all) - Track all job IDs
  • Sets ({prefix}jobs:by_name:{name}) - Index jobs by name for fast lookup
  • Sorted Sets ({prefix}jobs:by_next_run_at) - Index jobs by nextRunAt for efficient scheduling
  • Strings ({prefix}jobs:single:{name}) - Track single-type jobs for upsert operations

Real-Time Notifications

Redis has built-in pub/sub capabilities. When a job is saved, a notification is published to all subscribing Agenda instances, triggering immediate job processing without waiting for the next poll interval.

This means:

  • Lower latency for job execution
  • Reduced polling overhead
  • Efficient cross-process coordination

Distributed Locking

The backend uses Redis WATCH/MULTI/EXEC transactions to atomically lock jobs for processing, preventing duplicate execution across multiple Agenda instances.

Job Logging

RedisBackend includes a built-in RedisJobLogger that stores structured job lifecycle events using Redis sorted sets and hashes. The logger is lightweight and only creates its keys on first use.

Automatic Usage

When you enable logging in Agenda, the backend's built-in logger is used automatically:

const agenda = new Agenda({
  backend: new RedisBackend({ connectionString: 'redis://localhost:6379' }),
  logging: true  // Uses RedisJobLogger automatically
});

Standalone Usage

You can also use RedisJobLogger independently — for example, to log to Redis while using a different backend for storage:

import { RedisJobLogger } from '@agendajs/redis-backend';
import Redis from 'ioredis';

const logger = new RedisJobLogger({
  redis: new Redis('redis://localhost:6379')
});

// Use with any backend
import { MongoBackend } from '@agendajs/mongo-backend';
const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  logging: logger
});

See the Agenda README for full logging documentation.

Persistence

By default, Redis keeps data in memory. For production use with Agenda, configure Redis persistence:

# In redis.conf
appendonly yes           # Enable AOF persistence
appendfsync everysec     # Sync to disk every second

Or use RDB snapshots:

save 900 1      # Save after 900 seconds if at least 1 key changed
save 300 10     # Save after 300 seconds if at least 10 keys changed
save 60 10000   # Save after 60 seconds if at least 10000 keys changed

For maximum durability, enable both AOF and RDB.

Testing

Tests require a Redis server. The easiest way is to use Docker:

# Start Redis container and run tests
pnpm test:docker

# Or manually:
pnpm docker:up      # Start Redis container
pnpm test           # Run tests
pnpm docker:down    # Stop container

You can also use an existing Redis server:

REDIS_TEST_URL=redis://localhost:6379 pnpm test

Available Scripts

ScriptDescription
pnpm testRun tests (requires Redis or Docker)
pnpm test:dockerStart container, run tests, stop container
pnpm docker:upStart Redis container
pnpm docker:downStop Redis container
pnpm docker:logsView container logs

Requirements

  • Node.js >= 18.0.0
  • Redis >= 6.0
  • Agenda >= 6.0.0

License

MIT

版本与发布记录

@agendajs/redis-backend 共发布 12 个版本,首次发布于 2026/01/26;过去 12 个月发布了 12 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.8latest2026/10/317 天前
3.0.72026/07/213 个月前
3.0.62026/05/095 个月前
3.0.52026/04/027 个月前
3.0.42026/03/078 个月前
3.0.32026/02/168 个月前

其他发布通道:alpha → 1.0.0-alpha.0。

关于 @agendajs/redis-backend 的常见问题

@agendajs/redis-backend 是什么?

Redis backend for Agenda job scheduler with Pub/Sub notification support

如何安装 @agendajs/redis-backend?

在项目目录运行 npm install @agendajs/redis-backend,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:agenda(6.2.7)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@agendajs/redis-backend 支持 TypeScript 吗?

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

@agendajs/redis-backend 支持 ESM 还是 CommonJS?

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

@agendajs/redis-backend 需要什么版本的 Node.js?

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

@agendajs/redis-backend 可以商用吗?

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

@agendajs/redis-backend 的下载量有多少?

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

@agendajs/redis-backend 还在维护吗?

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