修改缓存

This commit is contained in:
dcr_xuxgc
2026-06-12 18:55:06 +08:00
parent d759a9e740
commit 449b1417ec
5 changed files with 134 additions and 3 deletions

View File

@@ -200,8 +200,33 @@ function parseJSON(str, defaultValue) {
}
}
// 刷新缓存 - 从数据库重新加载所有数据
async function refreshCache() {
if (!pool) return false;
try {
const [posts] = await pool.execute('SELECT * FROM posts ORDER BY date DESC');
const [settings] = await pool.execute('SELECT * FROM settings WHERE id = 1');
const [about] = await pool.execute('SELECT * FROM about WHERE id = 1');
memoryStore.posts = posts;
if (settings.length > 0) {
memoryStore.settings = formatSettings(settings[0]);
}
if (about.length > 0) {
memoryStore.about = formatAbout(about[0]);
}
console.log('✅ 缓存已刷新');
return true;
} catch (error) {
console.error('缓存刷新失败:', error.message);
return false;
}
}
function getPool() {
return pool;
}
module.exports = { initDatabase, getPool };
module.exports = { initDatabase, getPool, refreshCache };

View File

@@ -18,12 +18,14 @@ const aboutRouter = require('./routes/about');
const settingsRouter = require('./routes/settings');
const cronRouter = require('./routes/cron');
const configRouter = require('./routes/config');
const cacheRouter = require('./routes/cache');
app.use('/api/posts', postsRouter);
app.use('/api/about', aboutRouter);
app.use('/api/settings', settingsRouter);
app.use('/api/cron-tasks', cronRouter);
app.use('/api/config', configRouter);
app.use('/api/cache', cacheRouter);
// 健康检查
app.get('/api/health', (req, res) => {

View File

@@ -0,0 +1,20 @@
const express = require('express');
const router = express.Router();
const { refreshCache } = require('../config/database');
// 刷新所有缓存posts, settings, about
router.post('/refresh', async (req, res) => {
try {
const success = await refreshCache();
if (success) {
res.json({ message: '缓存已刷新', success: true });
} else {
res.status(500).json({ error: '缓存刷新失败', success: false });
}
} catch (error) {
console.error('缓存刷新失败:', error);
res.status(500).json({ error: '缓存刷新失败', success: false });
}
});
module.exports = router;