You've already forked node-redis
mirror of
https://github.com/redis/node-redis.git
synced 2025-08-07 13:22:56 +03:00
Ping interval (#2321)
* fix #1598 fix #2276 - add `pingInterval` to client config * setPingTimer on ready (instead of on connect) * use isReady (instead of isOpen) and fix test * Update client-configuration.md
This commit is contained in:
@@ -25,6 +25,7 @@
|
||||
| readonly | `false` | Connect in [`READONLY`](https://redis.io/commands/readonly) mode |
|
||||
| legacyMode | `false` | Maintain some backwards compatibility (see the [Migration Guide](./v3-to-v4.md)) |
|
||||
| isolationPoolOptions | | See the [Isolated Execution Guide](./isolated-execution.md) |
|
||||
| pingInterval | | Send `PING` command at interval (in ms). Useful with "[Azure Cache for Redis](https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-best-practices-connection#idle-timeout)" |
|
||||
|
||||
## Reconnect Strategy
|
||||
|
||||
|
@@ -862,4 +862,16 @@ describe('Client', () => {
|
||||
client.unref();
|
||||
client.ref();
|
||||
}, GLOBAL.SERVERS.OPEN);
|
||||
|
||||
testUtils.testWithClient('pingInterval', async client => {
|
||||
assert.deepEqual(
|
||||
await once(client, 'ping-interval'),
|
||||
['PONG']
|
||||
);
|
||||
}, {
|
||||
...GLOBAL.SERVERS.OPEN,
|
||||
clientOptions: {
|
||||
pingInterval: 1
|
||||
}
|
||||
});
|
||||
});
|
||||
|
@@ -31,6 +31,7 @@ export interface RedisClientOptions<
|
||||
readonly?: boolean;
|
||||
legacyMode?: boolean;
|
||||
isolationPoolOptions?: PoolOptions;
|
||||
pingInterval?: number;
|
||||
}
|
||||
|
||||
type WithCommands = {
|
||||
@@ -281,9 +282,12 @@ export default class RedisClient<
|
||||
this.#queue.flushAll(err);
|
||||
}
|
||||
})
|
||||
.on('connect', () => this.emit('connect'))
|
||||
.on('connect', () => {
|
||||
this.emit('connect');
|
||||
})
|
||||
.on('ready', () => {
|
||||
this.emit('ready');
|
||||
this.#setPingTimer();
|
||||
this.#tick();
|
||||
})
|
||||
.on('reconnecting', () => this.emit('reconnecting'))
|
||||
@@ -348,6 +352,22 @@ export default class RedisClient<
|
||||
(...args: Array<unknown>): void => (this as any).sendCommand(name, ...args);
|
||||
}
|
||||
|
||||
#pingTimer?: NodeJS.Timer;
|
||||
|
||||
#setPingTimer(): void {
|
||||
if (!this.#options?.pingInterval || !this.#socket.isReady) return;
|
||||
clearTimeout(this.#pingTimer);
|
||||
|
||||
this.#pingTimer = setTimeout(() => {
|
||||
if (!this.#socket.isReady) return;
|
||||
|
||||
(this as unknown as RedisClientType<M, F, S>).ping()
|
||||
.then(reply => this.emit('ping-interval', reply))
|
||||
.catch(err => this.emit('error', err))
|
||||
.finally(() => this.#setPingTimer());
|
||||
}, this.#options.pingInterval);
|
||||
}
|
||||
|
||||
duplicate(overrides?: Partial<RedisClientOptions<M, F, S>>): RedisClientType<M, F, S> {
|
||||
return new (Object.getPrototypeOf(this).constructor)({
|
||||
...this.#options,
|
||||
|
Reference in New Issue
Block a user