Skip to content

Commit c7817be

Browse files
authored
Merge pull request #1449 from rocket-admin/backend_redis_improvements
refactor: improve Redis client connection handling and error management to prevent app shutdown
2 parents ee63916 + 61c75dd commit c7817be

File tree

1 file changed

+42
-15
lines changed

1 file changed

+42
-15
lines changed

shared-code/src/data-access-layer/data-access-objects/data-access-object-redis.ts

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,6 @@ export class DataAccessObjectRedis extends BasicDataAccessObject implements IDat
458458
try {
459459
const redisClient = await this.getClient();
460460
const response = await redisClient.ping();
461-
462461
if (response === 'PONG') {
463462
return {
464463
result: true,
@@ -855,23 +854,51 @@ export class DataAccessObjectRedis extends BasicDataAccessObject implements IDat
855854
? Number(this.connection.database)
856855
: 0
857856
: 0;
858-
if (!client) {
859-
client = createClient({
860-
socket: {
857+
try {
858+
if (!client) {
859+
const shouldUseTLS = this.connection.ssl !== false;
860+
861+
const socketConfig: any = {
861862
host: this.connection.host,
862863
port: this.connection.port,
863-
ca: this.connection.cert || undefined,
864-
cert: this.connection.cert || undefined,
865-
rejectUnauthorized: this.connection.ssl === false ? false : true,
866-
},
867-
password: this.connection.password || undefined,
868-
username: this.connection.username || undefined,
869-
database: database,
870-
});
871-
await client.connect();
872-
LRUStorage.setRedisClientCache(this.connection, client);
864+
reconnectStrategy: (retries: number) => {
865+
if (retries > 3) {
866+
return new Error('Max reconnection attempts reached');
867+
}
868+
return Math.min(retries * 100, 3000);
869+
},
870+
};
871+
872+
if (shouldUseTLS) {
873+
socketConfig.tls = true;
874+
socketConfig.rejectUnauthorized = this.connection.ssl === false ? false : true;
875+
876+
if (this.connection.cert) {
877+
socketConfig.ca = this.connection.cert;
878+
socketConfig.cert = this.connection.cert;
879+
}
880+
}
881+
882+
client = createClient({
883+
socket: socketConfig,
884+
password: this.connection.password || undefined,
885+
username: this.connection.username || undefined,
886+
database: database,
887+
});
888+
889+
client.on('error', (err) => {
890+
console.error('Redis Client Error:', err);
891+
LRUStorage.delRedisClientCache(this.connection);
892+
});
893+
894+
await client.connect();
895+
LRUStorage.setRedisClientCache(this.connection, client);
896+
}
897+
return client;
898+
} catch (error) {
899+
LRUStorage.delRedisClientCache(this.connection);
900+
throw error;
873901
}
874-
return client;
875902
}
876903

877904
private async createTunneledConnection(connection: ConnectionParams): Promise<RedisClientType> {

0 commit comments

Comments
 (0)