AWS rds postgres会话计数不断增加,服务器变得没有响应



使用的平台:

  1. 嵌套Js 7.1.2
  2. Postgres

经过一段时间后,我的aws-rds会话计数不断增加,服务器变得没有响应。我需要重新启动服务器以使其正常工作。

我的数据库连接代码在main.ts:

import * as session from 'express-session';
app.use(
session({
store: new (require('connect-pg-simple')(session))({
conString:
'pg://' +
process.env.TYPEORM_USERNAME +
':' +
process.env.TYPEORM_PASSWORD +
'@' +
process.env.TYPEORM_HOST +
'/' +
process.env.TYPEORM_DATABASE,
}),
secret: process.env.COOKIE_SECRET,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
}),
);

app.module.ts代码:

TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('database'),
inject: [ConfigService],
})

其中我的数据库配置如下:

import * as path from 'path';
export default {
type: process.env.TYPEORM_CONNECTION,
host: process.env.TYPEORM_HOST,
port: +process.env.TYPEORM_PORT,
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
database: process.env.TYPEORM_DATABASE,
synchronize: true,
dropSchema: false,
logging: false,
retryAttempts: 5,
keepConnectionAlive: true,
entities: [path.join(__dirname, '../') + '**/!(*.d).entity{.ts,.js}'],
migrations: ['migrations/**/*.ts'],
subscribers: ['subscriber/**/*.ts', 'dist/subscriber/**/.js'],
cli: {
entitiesDir: 'src',
migrationsDir: 'migrations',
subscribersDir: 'subscriber',
},
};

请协助。。。在这件事上挣扎了很多!!

使用pgPromise连接参数而不是conString参数。同时修改apolloServer+express会话配置设置。

async function main() {
const connection = await createConnection(ormconfig as ConnectionOptions);

const schema = await buildSchema({ resolvers: [DysfunctionalThoughtResolver,UserResolver] });
const server = new ApolloServer({ 
schema,
context: async ({ req, res }) => ({ req, res }),
playground: {
settings: {
"request.credentials": "same-origin",
}
}
});
var app=express();
var pgSession = require('connect-pg-simple')(session);
app.use(session({
name: process.env.COOKIE_NAME,
saveUninitialized:false,
secret:process.env.COOKIE_SECRET?.split(','),
cookie: {
store: new pgSession({
pgPromise : connection
}),
httpOnly: true,
secure: process.env.NODE_ENV=="prod",
sameSite: true,
maxAge: 600000 // Time is in miliseconds
},
resave: false
}))
await app.listen({port:4000});
server.applyMiddleware({ app });
console.log("Server has started!");
}
main();

不要忘记在connect pg simple:中添加所需的会话表

https://github.com/voxpelli/node-connect-pg-simple/blob/HEAD/table.sql

CREATE TABLE "session" (
"sid" varchar NOT NULL COLLATE "default",
"sess" json NOT NULL,
"expire" timestamp(6) NOT NULL
)
WITH (OIDS=FALSE);
ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;
CREATE INDEX "IDX_session_expire" ON "session" ("expire");

TypeORM翻译(放在模型/实体文件夹中的session.ts文件中(。

@Entity()
export class session {
@PrimaryColumn({
type: "varchar",
nullable: false,
//collation:"" //needed?
})
sid:string;
@Column({
type: "json",
nullable: false
})
sess:any;
@Index("IDX_session_expire")
@Column({
type: "timestamp",
precision: 6,
nullable: false
})
expire:Date;
}

然后在你的解析器中访问它

@Mutation(() => String)
async login(@Args() { email, password }: UserLoginArgs, @Ctx() ctx: any) {
let response = "";
let sess = ctx.req.session;
if (sess.userId) { response = "already logged in"; }
else {
let user = await User.findOne({ where: { email: email } });
if (user) {
let passwordsMatch = await bcrypt.compare(password, user?.password);
if (passwordsMatch) {
sess.userId = user.id;
sess.save();
response = "login successful";
} else {
response = "Password doesn't match"
}
} else {
response = "User not found";
}
}
return response;
}
@Mutation(() => String)
async logout(@Ctx() ctx: any) {
let sess = ctx.req.session;
if (!sess.userId) { return "already logged out"; }
else{
sess.destroy();
return "logged out";
}
}

最新更新