生产使用
准备好你的Node.js应用程序以投入生产
以下部分解释了如何处理生产环境中可能出现的情况。
处理错误
Node-Redis 提供了 多个事件来处理各种场景,其中最关键的是 error
事件。
每当客户端内发生错误时,都会触发此事件。
监听错误事件至关重要。
如果客户端没有注册至少一个错误监听器并且发生错误,系统将抛出该错误,可能导致Node.js进程意外退出。 详情请参阅EventEmitter文档。
const client = createClient({
// ... client options
});
// Always ensure there's a listener for errors in the client to prevent process crashes due to unhandled errors
client.on('error', error => {
console.error(`Redis client error:`, error);
});
处理重新连接
如果网络问题或其他问题意外关闭了套接字,客户端将拒绝所有已发送的命令,因为服务器可能已经执行了它们。
其余待处理的命令将保留在内存中排队,直到建立新的套接字。
此行为由enableOfflineQueue
选项控制,该选项默认启用。
客户端使用reconnectStrategy
来决定何时尝试重新连接。
默认策略是根据尝试次数Math.min(retries * 50, 500)
计算每次尝试前的延迟。您可以通过向reconnectStrategy
选项传递支持的值来自定义此策略:
- 定义一个回调函数
(retries: number, cause: Error) => false | number | Error
(推荐)
const client = createClient({
socket: {
reconnectStrategy: function(retries) {
if (retries > 20) {
console.log("Too many attempts to reconnect. Redis connection was terminated");
return new Error("Too many retries.");
} else {
return retries * 500;
}
}
}
});
client.on('error', error => console.error('Redis client error:', error));
在提供的重连策略回调中,客户端尝试最多重连20次,每次尝试之间的延迟为retries * 500
毫秒。
大约两分钟后,如果超过最大重试限制,客户端将记录错误消息并终止连接。
- 使用数值来设置以毫秒为单位的固定延迟。
- 使用
false
来禁用重新连接尝试。此选项仅应用于测试目的。
超时
要为连接设置超时,请使用 connectTimeout
选项:
const client = createClient({
socket: {
// setting a 10-second timeout
connectTimeout: 10000 // in milliseconds
}
});
client.on('error', error => console.error('Redis client error:', error));