Server.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. const express = require('express')
  2. const cors = require('cors')
  3. const path = require('path')
  4. const fs = require('fs')
  5. const config = require('../config.json')
  6. const Logger = require('./Logger')
  7. const MySQL = require('../plugin/DataBase/MySQL')
  8. const Worker = require('./Lepao/Worker')
  9. const mq = require('../plugin/mq')
  10. const { startLepaoSchedulePublisher } = require('../plugin/mq/lepaoSchedulePublisher')
  11. class SERVER {
  12. constructor() {
  13. this.app = express()
  14. this.port = config.port || 3000
  15. this.apiDirectory = path.join(__dirname, '../apis') // API 文件存放目录
  16. this.logger = new Logger(path.join(__dirname, '../logs/Server.log'), 'INFO')
  17. // 解析 JSON 请求体
  18. this.app.use(express.json())
  19. //解决cors跨域
  20. this.app.use(cors())
  21. //使用静态资源
  22. this.app.use('/uploads', express.static('./uploads'))
  23. this.app.use('/models', express.static('./models'))
  24. // 初始化数据库连接
  25. this.db = new MySQL()
  26. // 加载 API 路由
  27. this.loadAPIs(this.apiDirectory)
  28. }
  29. // 测试数据库连接
  30. async initDB() {
  31. try {
  32. this.logger.info('正在测试数据库连接')
  33. await this.db.connect()
  34. await this.db.close()
  35. } catch (error) {
  36. this.logger.error(`数据库连接失败: ${error.stack}`)
  37. process.exit(1)
  38. }
  39. }
  40. // 测试MQ连接
  41. async initMQ() {
  42. try {
  43. await mq.init()
  44. const ch = await mq.getChannel('health')
  45. await ch.assertQueue('mq_health_check', { durable: false })
  46. this.logger.info('✅ RabbitMQ 初始化 & 测试成功')
  47. const worker = new Worker()
  48. try {
  49. await worker.start()
  50. this.logger.info('RunForge Worker 已启动,正在监听 MQ 任务...')
  51. startLepaoSchedulePublisher({
  52. logger: this.logger,
  53. intervalMs: config.rabbitmq?.lepaoScheduleTickMs ?? 2000,
  54. batch: config.rabbitmq?.lepaoScheduleBatch ?? 100
  55. })
  56. } catch (err) {
  57. console.error('RunForge Worker 启动失败:', err)
  58. process.exit(1)
  59. }
  60. } catch (e) {
  61. this.logger.error('❌ RabbitMQ 初始化失败')
  62. process.exit(1)
  63. }
  64. }
  65. loadAPIs(directory) {
  66. const items = fs.readdirSync(directory)
  67. items.forEach(item => {
  68. const itemPath = path.join(directory, item)
  69. const stats = fs.statSync(itemPath)
  70. if (stats.isDirectory()) {
  71. // 如果是目录,递归调用
  72. this.loadAPIs(itemPath)
  73. } else if (stats.isFile() && itemPath.endsWith('.js')) {
  74. // 如果是文件且是 JavaScript 文件
  75. this.loadAPIFile(itemPath)
  76. }
  77. })
  78. }
  79. // 加载单个 API 文件
  80. loadAPIFile(filePath) {
  81. try {
  82. const APIClass = require(filePath)
  83. for (const key in APIClass) {
  84. if (APIClass.hasOwnProperty(key)) {
  85. const apiInstance = new APIClass[key]()
  86. apiInstance.setupRoute()
  87. this.app.use('/', apiInstance.getRouter())
  88. this.logger.info(`已加载API:${apiInstance.path} 类型:${apiInstance.method}`)
  89. }
  90. }
  91. } catch (error) {
  92. this.logger.error(`加载API文件失败: ${filePath},错误: ${error.stack}`)
  93. }
  94. }
  95. start() {
  96. this.logger.info('============正在启动服务器============')
  97. // 初始化数据库连接
  98. this.initDB().then(() => {
  99. this.initMQ().then(() => {
  100. this.app.listen(this.port, () => {
  101. this.logger.info(`==========服务器正在 ${this.port} 端口上运行==========`)
  102. })
  103. }).catch(err => {
  104. this.logger.error(`启动服务器失败: ${err.message}`)
  105. })
  106. }).catch(err => {
  107. this.logger.error(`启动服务器失败: ${err.message}`)
  108. process.exit(1) // 启动失败时退出进程
  109. })
  110. }
  111. }
  112. module.exports = SERVER