init redis lazy

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-07-20 20:17:32 +02:00
parent 492141547d
commit f2298a1b05
19 changed files with 134 additions and 86 deletions

View File

@@ -1,4 +1,4 @@
import { redis } from './redis';
import { getRedisCache } from './redis';
export function cacheable<T extends (...args: any) => any>(
fn: T,
@@ -9,7 +9,7 @@ export function cacheable<T extends (...args: any) => any>(
): Promise<Awaited<ReturnType<T>>> {
// JSON.stringify here is not bullet proof since ordering of object keys matters etc
const key = `cachable:${fn.name}:${JSON.stringify(args)}`;
const cached = await redis.get(key);
const cached = await getRedisCache().get(key);
if (cached) {
try {
return JSON.parse(cached);
@@ -20,7 +20,7 @@ export function cacheable<T extends (...args: any) => any>(
const result = await fn(...(args as any));
if (result !== undefined || result !== null) {
redis.setex(key, expire, JSON.stringify(result));
getRedisCache().setex(key, expire, JSON.stringify(result));
}
return result;

View File

@@ -2,12 +2,65 @@ import type { RedisOptions } from 'ioredis';
import Redis from 'ioredis';
const options: RedisOptions = {
connectTimeout: 30000,
maxRetriesPerRequest: null,
connectTimeout: 10000,
};
export { Redis };
export const redis = new Redis(process.env.REDIS_URL!, options);
export const redisSub = new Redis(process.env.REDIS_URL!, options);
export const redisPub = new Redis(process.env.REDIS_URL!, options);
const createRedisClient = (
url: string,
overrides: RedisOptions = {}
): Redis => {
const client = new Redis(url, { ...options, ...overrides });
client.on('error', (error) => {
console.error('Redis Client Error:', error);
});
return client;
};
let redisCache: Redis;
export function getRedisCache() {
if (!redisCache) {
redisCache = createRedisClient(process.env.REDIS_URL!, options);
}
return redisCache;
}
let redisSub: Redis;
export function getRedisSub() {
if (!redisSub) {
redisSub = createRedisClient(process.env.REDIS_URL!, options);
}
return redisSub;
}
let redisPub: Redis;
export function getRedisPub() {
if (!redisPub) {
redisPub = createRedisClient(process.env.REDIS_URL!, options);
}
return redisPub;
}
let redisQueue: Redis;
export function getRedisQueue() {
if (!redisQueue) {
// Use different redis for queues (self-hosting will re-use the same redis instance)
redisQueue = createRedisClient(
(process.env.QUEUE_REDIS_URL || process.env.REDIS_URL)!,
{
...options,
enableReadyCheck: false,
maxRetriesPerRequest: null,
enableOfflineQueue: true,
}
);
}
return redisQueue;
}