-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
84 lines (68 loc) · 2.31 KB
/
server.js
File metadata and controls
84 lines (68 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const app = require('./src/app');
const { connectDB, closeDB } = require('./src/config/database');
const PORT = process.env.PORT || 3000;
/**
* 启动服务器
*/
const startServer = async () => {
try {
console.log('🚀 正在启动 FRKB API 服务器...');
// 1. 连接数据库
console.log('📡 正在连接数据库...');
await connectDB();
// 2. 启动HTTP服务器
const server = app.listen(PORT, () => {
console.log('🎉 服务器启动成功!');
console.log(`📍 本地地址: http://localhost:${PORT}`);
console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
console.log(`🔗 健康检查: http://localhost:${PORT}/health`);
console.log(`📚 API前缀: ${process.env.API_PREFIX || '/frkbapi/v1'}`);
console.log('─'.repeat(50));
});
// 设置服务器超时
server.timeout = 30000; // 30秒
// 保存server实例用于优雅关闭
global.server = server;
} catch (error) {
console.error('❌ 服务器启动失败:', error.message);
process.exit(1);
}
};
/**
* 优雅关闭服务器
*/
const gracefulShutdown = async (signal) => {
console.log(`\n🛑 接收到 ${signal} 信号,正在优雅关闭服务器...`);
try {
// 1. 停止接收新请求
if (global.server) {
console.log('⏹️ 正在关闭HTTP服务器...');
global.server.close(() => {
console.log('✅ HTTP服务器已关闭');
});
}
// 2. 关闭数据库连接
console.log('🔌 正在关闭数据库连接...');
await closeDB();
console.log('✨ 服务器已优雅关闭');
process.exit(0);
} catch (error) {
console.error('❌ 关闭服务器时出错:', error.message);
process.exit(1);
}
};
// 监听进程信号,实现优雅关闭
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// 监听未捕获的异常
process.on('uncaughtException', (error) => {
console.error('❌ 未捕获的异常:', error);
gracefulShutdown('uncaughtException');
});
process.on('unhandledRejection', (reason, promise) => {
console.error('❌ 未处理的Promise拒绝:', reason);
console.error('Promise:', promise);
gracefulShutdown('unhandledRejection');
});
// 启动服务器
startServer();