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

如何在AWS Lambda中使用NestJS的createMicroservice工厂?

在AWS Lambda中传递SQS事件给NestJS微服务实例

要在无服务器Lambda环境下将SQS事件传递给NestJS微服务实例,无需依赖listen()方法,可采用以下两种方案:

方案1:直接调用服务类处理方法(最简实现)

如果不需要复用Nest微服务的消息路由机制,直接获取业务处理服务并调用方法即可:

1. 创建SQS事件处理服务

在NestJS中定义负责处理SQS事件的Injectable服务:

import { Injectable } from '@nestjs/common';
import { SQSEvent } from 'aws-lambda';

@Injectable()
export class SqsEventProcessor {
  async handleSqsEvent(event: SQSEvent): Promise<any> {
    // 解析SQS事件,批量处理消息
    return Promise.all(
      event.Records.map(async (record) => {
        const messageBody = JSON.parse(record.body);
        // 这里编写你的业务逻辑
        return {
          messageId: record.messageId,
          processedData: messageBody,
          status: 'completed'
        };
      })
    );
  }
}

2. 在Lambda Handler中调用服务

修改Lambda的lambda.ts代码,缓存Nest应用实例并调用处理服务:

import { INestApplicationContext, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { CustomStrategy } from '@nestjs/microservices';
import { SQSEvent, Context } from 'aws-lambda';

let cachedApp: INestApplicationContext;

async function bootstrap(): Promise<INestApplicationContext> {
  if (!cachedApp) {
    // 创建微服务实例,使用空自定义策略避免监听端口
    cachedApp = await NestFactory.createMicroservice(AppModule, {
      strategy: {
        listen: () => Promise.resolve(),
        close: () => Promise.resolve(),
      } as CustomStrategy,
    });
    await cachedApp.init();
  }
  return cachedApp;
}

export const sqsHandler = async (event: SQSEvent, context: Context) => {    
  const app = await bootstrap();    
  // 获取处理服务实例并调用方法
  const processor = app.get(SqsEventProcessor);
  const result = await processor.handleSqsEvent(event);
  
  // 返回Lambda响应(可根据需求调整格式)
  return {
    statusCode: 200,
    body: JSON.stringify(result),
  };
};

方案2:利用NestJS微服务消息模式(适合路由场景)

如果需要复用Nest微服务的@MessagePattern进行消息路由,可通过app.send()触发对应处理器:

1. 创建带消息模式的控制器

定义带有@MessagePattern装饰器的控制器,指定消息路由标识:

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { SQSEvent } from 'aws-lambda';

@Controller()
export class SqsMessageController {
  @MessagePattern('process-sqs-event')
  async processEvent(event: SQSEvent): Promise<any> {
    // 处理SQS事件逻辑
    return event.Records.map(record => ({
      messageId: record.messageId,
      body: JSON.parse(record.body),
      processedAt: new Date().toISOString()
    }));
  }
}

2. 在Lambda Handler中触发消息处理

使用app.send()方法通过消息标识触发对应处理器:

import { INestApplicationContext, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { CustomStrategy } from '@nestjs/microservices';
import { SQSEvent, Context } from 'aws-lambda';

let cachedApp: INestApplicationContext;

async function bootstrap(): Promise<INestApplicationContext> {
  if (!cachedApp) {
    cachedApp = await NestFactory.createMicroservice(AppModule, {
      strategy: {
        listen: () => Promise.resolve(),
        close: () => Promise.resolve(),
      } as CustomStrategy,
    });
    await cachedApp.init();
  }
  return cachedApp;
}

export const sqsHandler = async (event: SQSEvent, context: Context) => {    
  const app = await bootstrap();    
  // 通过消息模式触发处理器
  const result = await app.send('process-sqs-event', event);
  
  return {
    statusCode: 200,
    body: JSON.stringify(result),
  };
};

核心注意事项

  • 缓存应用实例:Lambda会复用执行环境,缓存cachedApp可避免每次请求重新初始化Nest应用,大幅提升性能。
  • 自定义空策略:使用CustomStrategy的空实现,避免微服务尝试监听端口(Lambda环境无需端口监听)。
  • SQS事件解析:SQS事件的Records数组中,每个消息的body通常为JSON字符串,需自行解析为业务对象。
  • 资源管理:Lambda执行完成后,应用实例会保留在缓存中,无需手动关闭,除非有特定资源需要释放。

内容的提问来源于stack exchange,提问作者Vingtoft

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:31:08