Created
September 5, 2024 16:56
-
-
Save thatbeautifuldream/0163c57b2a08896e2de8c9f21eada746 to your computer and use it in GitHub Desktop.
Redis Singleton for Next.js App router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { createClient } from "redis"; | |
| import { env } from "~/env"; | |
| class RedisClient { | |
| private static instance: ReturnType<typeof createClient> | null = null; | |
| private static connectionCount: number = 0; | |
| private constructor() {} | |
| public static async getInstance(): Promise<ReturnType<typeof createClient>> { | |
| if (!RedisClient.instance) { | |
| console.log("Creating new Redis connection..."); | |
| RedisClient.instance = createClient({ | |
| url: `redis://${env.REDIS_HOST}:${env.REDIS_PORT}`, | |
| }); | |
| await RedisClient.instance.connect(); | |
| RedisClient.connectionCount++; | |
| console.log( | |
| `Redis connection established. Connection count: ${RedisClient.connectionCount}` | |
| ); | |
| } else { | |
| console.log( | |
| `Reusing existing Redis connection. Connection count: ${RedisClient.connectionCount}` | |
| ); | |
| } | |
| return RedisClient.instance; | |
| } | |
| public static getConnectionCount(): number { | |
| return RedisClient.connectionCount; | |
| } | |
| public static async closeConnection(): Promise<void> { | |
| if (RedisClient.instance) { | |
| await RedisClient.instance.quit(); | |
| RedisClient.instance = null; | |
| RedisClient.connectionCount = 0; | |
| console.log("Redis connection closed."); | |
| } | |
| } | |
| } | |
| export default RedisClient; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment