You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Azure Identity配置Nest.js Bull连接Azure Redis缓存

解决方案

要将Azure AD令牌认证的Redis客户端整合到Nest.js Bull模块中,核心是实现createClient工厂函数,该函数需要异步获取Azure AD令牌并创建配置好的Redis客户端实例。以下是完整的实现步骤和代码:

1. 核心逻辑说明

Bull的createClient是一个回调函数,接收type(client或subscriber)和可选的redisOpts参数,需要返回一个已连接(或可自动连接)的Redis客户端实例。由于Azure AD令牌需要异步获取,我们需要将useFactory设为异步函数,并在其中封装令牌获取和客户端创建逻辑。

2. 完整配置代码

import { BullModule } from '@nestjs/bull';
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";

// 定义Redis范围和Azure Redis配置常量
const REDIS_SCOPE = "acca5fbb-b7e4-4009-81f1-37e38fd66d78/.default";
const REDIS_USERNAME = 'xxx-xxx-xxx';
const REDIS_URL = `redis://xxxx-domain.redis.cache.windows.net:6380`;

const bullConfig = {
  useFactory: async () => ({
    createClient: async (type: 'client' | 'subscriber') => {
      // 获取Azure AD访问令牌
      const credential = new DefaultAzureCredential();
      const accessToken = await credential.getToken(REDIS_SCOPE);
      if (!accessToken?.token) {
        throw new Error('Failed to retrieve Azure AD access token for Redis');
      }

      // 创建Redis客户端
      const client = createClient({
        username: REDIS_USERNAME,
        password: accessToken.token,
        url: REDIS_URL,
        pingInterval: 100000,
        socket: {
          tls: true,
          keepAlive: 0
        },
      });

      // 监听错误
      client.on("error", (err) => console.error("Redis Client Error", err));

      // 连接客户端
      await client.connect();

      return client;
    },
  }),
};

@Global()
@Module({
  imports: [
    BullModule.forRootAsync(bullConfig),
    BullModule.registerQueue({
      name: USER_EMBEDDED_DATA_UPDATE,
    })
  ],
  exports: [BullModule],
})
export class SharedBullModule { }

3. 注意事项

  • 令牌有效期处理:Azure AD令牌默认有有效期(通常1小时),如果应用运行时间较长,需要实现令牌刷新逻辑,避免令牌过期后Redis连接失败。可以通过定时重新获取令牌并创建新客户端,或在客户端错误回调中尝试刷新令牌并重连。
  • 客户端类型兼容:Bull需要client和subscriber两种客户端,上述代码中两种类型使用相同配置,这在Azure Redis环境中是可行的,因为Azure Redis支持同一连接同时处理命令和订阅。
  • 依赖安装:确保已安装所需依赖:@nestjs/bull、bull、redis、@azure/identity。

内容的提问来源于stack exchange,提问作者Code The World

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:35:14