const Koa = require("koa"); const Router = require("@koa/router"); const mysql = require("mysql2/promise"); const Redis = require("redis"); require("dotenv").config(); const app = new Koa(); const router = new Router(); // MySQL 连接 const pool = mysql.createPool({ host: process.env.MYSQL_HOST, user: process.env.MYSQL_USER, password: process.env.MYSQL_PASSWORD, database: process.env.MYSQL_DATABASE, waitForConnections: true, connectionLimit: 10, queueLimit: 0, }); // Redis 客户端 const redisClient = Redis.createClient({ url: `redis://${process.env.REDIS_HOST || 'localhost'}:${process.env.REDIS_PORT || 6379}`, }); redisClient.on("error", (err) => console.log("Redis Client Error", err)); // 连接 Redis (async () => { await redisClient.connect(); })(); // 示例路由 router.get("/", async (ctx) => { ctx.body = "Welcome to Koa Docker Demo!"; }); // 读写 MySQL 数据的示例路由 router.get("/users", async (ctx) => { const [rows] = await pool.query("SELECT * FROM users"); ctx.body = rows; }); // 读写 Redis 数据的示例路由 router.get("/visits", async (ctx) => { let visits = await redisClient.get("visits"); visits = parseInt(visits) || 0; await redisClient.set("visits", visits + 1); ctx.body = { visits: visits + 1 }; }); // 手动执行 SQL 脚本的路由,用于模拟初始化数据库 router.get("/init-db", async (ctx) => { try { const sqlScript = await fs.readFile( path.join(__dirname, "../mysql-init/init.sql"), "utf8" ); await pool.query(sqlScript); ctx.body = { message: "Database initialized successfully" }; } catch (error) { console.error("Error initializing database:", error); ctx.status = 500; ctx.body = { error: "Failed to initialize database" }; } }); app.use(router.routes()).use(router.allowedMethods()); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });