我遇到了一个严重的问题。几个请求后,NestJS停止工作。我正在使用邮递员进行特定的API调用,然后,在对同一路由的请求少于10个之后,它变得非常慢,并且每次都会使邮递员超时。
main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {Logger} from '@nestjs/common'
import * as rateLimit from 'express-rate-limit';
import { WrapContentInterceptor } from './dashboard/dashboard.interceptors';
const PORT = 5000
const TAG = 'main'
async function bootstrap() {
const logger = new Logger(TAG)
const app = await NestFactory.create(AppModule);
// app.useGlobalInterceptors(new WrapContentInterceptor())
app.enableCors()
await app.listen(PORT);
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 1000, // limit each IP to 100 requests per windowMs
}),
);
logger.log(`listening port::${PORT}`)
}
bootstrap();
出现问题的控制器:
// some regular imports
@Controller('dashboard')
@UseGuards(AuthGuard()) // protecting routes
export class DashboardController {
constructor(
private dashboardService:DashboardService,
){}
// other routes
@Get('/cockpit/general-numbers') // route that i'm getting the issue
async getNumbersForCockpit(
@Query('desiredDate',ParseStringToDatePipe) desiredDay?:Date
):Promise<GeneralNumbersForCockpit>{
this.logger.log(`getNumbersForCockpit::${desiredDay.toISOString()}`)
let installation = await this.dashboardService.getInstallationsOfDay(desiredDay?desiredDay:undefined)
let averageTicket = await this.dashboardService.getAverageTicketPlanFromInterval(
desiredDay?getFirstDayOfMonth(desiredDay):undefined,
desiredDay?desiredDay:undefined
)
return {
averageTicket:averageTicket,
installation:installation.result
}
}
}
async getData(dateField:Date=new Date()):Promise<SimpleNumericalData>{
// this.logger.debug(`f::dateField:${dateField}`)
this.logger.debug(`getData::dateField:${dateField.toISOString()}`)
const queryRunner = this.connection.createQueryRunner()
let res = await queryRunner.manager.query(`
select count(*) as result from my_table
where my_field ='I'
and DATE(date_field) = DATE('${dateField.toISOString()}')
`)
//await this.connection.close()
// this.logger.debug(`Result:${JSON.stringify(res)}`)
return {
result:Number(res[0]['result'])
}
}
答案 0 :(得分:1)
我想您的问题来自您使用数据库连接的方式。您创建了〜6或10个与db的连接,但没有释放它们,并且mariadb的连接池的默认限制为10(我想)。
最后,新请求要创建新的连接,但是达到了限制,等待另一个连接的新请求被释放,但是它永远等待着。
在这种情况下,您可以扩展限制(不是根本原因,但我想知道是个好消息)。
在connectionLimit
的{{1}}下添加extra
(或在其中创建数据库配置的地方)
ormconfig.json
在查询完成(成功或错误)之后,您必须释放刚在{
...,
"extra": { connectionLimit: 10, ... }
}
函数中创建的新连接:
getData
注意:让我们注意查询何时抛出错误,可以使用try / catch / finally
...
...
await queryRunner.release()