68 lines
1.6 KiB
JavaScript
68 lines
1.6 KiB
JavaScript
import Redis from "ioredis";
|
|
|
|
let _redis = null;
|
|
|
|
function getRedis() {
|
|
if (!_redis) {
|
|
_redis = new Redis({
|
|
host: process.env.REDIS_HOST || "127.0.0.1",
|
|
port: parseInt(process.env.REDIS_PORT || "6379"),
|
|
password: process.env.REDIS_PASSWORD || undefined,
|
|
db: parseInt(process.env.REDIS_DB || "1"),
|
|
lazyConnect: true,
|
|
maxRetriesPerRequest: 2,
|
|
retryStrategy: (times) => Math.min(times * 200, 3000),
|
|
});
|
|
_redis.on("error", (err) => {
|
|
console.warn(`[redis-cache] Connection error: ${err.message}`);
|
|
});
|
|
}
|
|
return _redis;
|
|
}
|
|
|
|
async function cacheGet(key) {
|
|
try {
|
|
const redis = getRedis();
|
|
if (redis.status !== "ready") {
|
|
await redis.connect().catch(() => {});
|
|
}
|
|
if (redis.status !== "ready") return null;
|
|
const data = await redis.get(key);
|
|
return data ? JSON.parse(data) : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function cacheSet(key, value, ttlSeconds = 3600) {
|
|
try {
|
|
const redis = getRedis();
|
|
if (redis.status !== "ready") {
|
|
await redis.connect().catch(() => {});
|
|
}
|
|
if (redis.status !== "ready") return;
|
|
await redis.set(key, JSON.stringify(value), "EX", ttlSeconds);
|
|
} catch {
|
|
// 静默失败,不影响主流程
|
|
}
|
|
}
|
|
|
|
async function cacheDel(key) {
|
|
try {
|
|
const redis = getRedis();
|
|
if (redis.status !== "ready") return;
|
|
await redis.del(key);
|
|
} catch {
|
|
// 静默失败
|
|
}
|
|
}
|
|
|
|
async function disconnectRedis() {
|
|
if (_redis) {
|
|
await _redis.quit().catch(() => {});
|
|
_redis = null;
|
|
}
|
|
}
|
|
|
|
export { getRedis, cacheGet, cacheSet, cacheDel, disconnectRedis };
|