NestJS Serverless - App不断重新启动自己



我正在尝试设置一个NestJS无服务器应用程序。该应用程序从sls offline start开始运行良好。但问题是,这个应用程序一直在重新启动自己。未设置缓存服务器。每次调用端点时,服务器都会重新启动。

λ

import { Handler, Context } from 'aws-lambda';
import { Server } from 'http';
import { createServer, proxy } from 'aws-serverless-express';
import { eventContext } from 'aws-serverless-express/middleware';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import express from "express";
let cachedServer: Server;
async function bootstrapServer(): Promise<Server> {
console.log("cached?", !!cachedServer);
if (!cachedServer) {
const expressApp = express();
const nestApp = await NestFactory.create(AppModule, new ExpressAdapter(expressApp))
nestApp.use(eventContext());
await nestApp.init();

// here is the set
cachedServer = createServer(expressApp);
}
return cachedServer;
}
export const handler: Handler = async (event: any, context: Context) => {
// here is another set
cachedServer = await bootstrapServer();
return proxy(cachedServer, event, context, 'PROMISE').promise;
}

ANY /dev (λ: graphql)
cached? false
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [NestFactory] Starting Nest application... +186ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [InstanceLoader] AppModule dependencies initialized +3ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [RoutesResolver] AppController {/}: +0ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [RouterExplorer] Mapped {/, GET} route +1ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [NestApplication] Nest application successfully started +0ms
(λ: graphql) RequestId: cl3r0i9bu000b49v67zkk50gl  Duration: 12.56 ms  Billed Duration: 13 ms

ANY /dev (λ: graphql)
cached? false
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [NestFactory] Starting Nest application... +188ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [InstanceLoader] AppModule dependencies initialized +3ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [RoutesResolver] AppController {/}: +1ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [RouterExplorer] Mapped {/, GET} route +0ms
[Nest] 24777  - 05/29/2022, 9:00:31 AM     LOG [NestApplication] Nest application successfully started +0ms
(λ: graphql) RequestId: cl3r0i9h5000e49v65mfs21vo  Duration: 15.21 ms  Billed Duration: 16 ms

有人有什么想法吗?

EDIT:

——allowCache现在是>= 9.0.0的默认行为

老答:

从文档:Serverless-offline是一个模拟lambda和api-gateway的插件。

意味着不是执行环境,它将表现得好像你每次都调用一个冷函数。你需要添加一个选项来让它作为一个真正的函数来工作。

sls offline start --allowCache 

相关内容

  • 没有找到相关文章

最新更新