添加valkey support
This commit is contained in:
59
server/cache.js
Normal file
59
server/cache.js
Normal file
@@ -0,0 +1,59 @@
|
||||
const Redis = require('ioredis');
|
||||
|
||||
const host = process.env.VALKEY_HOST || 'localhost';
|
||||
const port = parseInt(process.env.VALKEY_PORT) || 6379;
|
||||
const password = process.env.VALKEY_PASSWORD || undefined;
|
||||
const db = parseInt(process.env.VALKEY_DB) || 0;
|
||||
const ttl = parseInt(process.env.VALKEY_TTL) || 30;
|
||||
|
||||
let redis = null;
|
||||
|
||||
try {
|
||||
redis = new Redis({
|
||||
host,
|
||||
port,
|
||||
password,
|
||||
db,
|
||||
lazyConnect: true,
|
||||
maxRetriesPerRequest: 1
|
||||
});
|
||||
|
||||
redis.on('error', (err) => {
|
||||
// Fail silently after one retry, we just won't cache
|
||||
console.warn('[Cache] Valkey connection failed, caching disabled:', err.message);
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[Cache] Valkey init failed:', err.message);
|
||||
}
|
||||
|
||||
const cache = {
|
||||
async get(key) {
|
||||
if (!redis) return null;
|
||||
try {
|
||||
const data = await redis.get(key);
|
||||
return data ? JSON.parse(data) : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
async set(key, value, customTtl = ttl) {
|
||||
if (!redis) return;
|
||||
try {
|
||||
await redis.set(key, JSON.stringify(value), 'EX', customTtl);
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
},
|
||||
|
||||
async del(key) {
|
||||
if (!redis) return;
|
||||
try {
|
||||
await redis.del(key);
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = cache;
|
||||
@@ -4,6 +4,7 @@ const cors = require('cors');
|
||||
const path = require('path');
|
||||
const db = require('./db');
|
||||
const prometheusService = require('./prometheus-service');
|
||||
const cache = require('./cache');
|
||||
const checkAndFixDatabase = require('./db-integrity-check');
|
||||
|
||||
const app = express();
|
||||
@@ -462,12 +463,20 @@ app.get('/api/metrics/overview', async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
const allMetrics = await Promise.all(sources.map(source =>
|
||||
prometheusService.getOverviewMetrics(source.url, source.name).catch(err => {
|
||||
const allMetrics = await Promise.all(sources.map(async (source) => {
|
||||
const cacheKey = `source_metrics:${source.url}:${source.name}`;
|
||||
const cached = await cache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
const metrics = await prometheusService.getOverviewMetrics(source.url, source.name);
|
||||
await cache.set(cacheKey, metrics, 15); // Cache for 15s
|
||||
return metrics;
|
||||
} catch (err) {
|
||||
console.error(`Error fetching metrics from ${source.name}:`, err.message);
|
||||
return null;
|
||||
})
|
||||
));
|
||||
}
|
||||
}));
|
||||
|
||||
const validMetrics = allMetrics.filter(m => m !== null);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user