Permalink
Browse files

Implement application-level idle ping

  • Loading branch information...
1 parent 62cbaa5 commit dca1aff864fe16511700983d857e60f43878d4d1 @mscdex committed Sep 23, 2012
Showing with 19 additions and 3 deletions.
  1. +2 −2 README.md
  2. +17 −1 lib/Client.js
View
@@ -284,6 +284,8 @@ Client methods
* **connTimeout** - <_integer_> - Number of seconds to wait for a connection to be made. **Default:** 10
+ * **pingInterval** - <_integer_> - Number of seconds between pings while idle. **Default:** 300
+
* **secureAuth** - <_boolean_> - Use password hashing available in MySQL 4.1.1+ when authenticating. **Default:** true
* **compress** - <_boolean_> - Use connection compression? **Default:** false
@@ -362,8 +364,6 @@ TODO
* Auto-reconnect algorithm(s) ?
-* Periodic ping to keep connection alive
-
* API to execute "KILL QUERY _client_threadId_" easily
* Possibly some other stuff I'm not aware of at the moment
View
@@ -34,6 +34,8 @@ function Client() {
this.queryCache.keys = {};
this.threadId = undefined;
this.connected = false;
+ this.pingInterval = 300000;
+ this._pinger = undefined;
this._closeOnEmpty = false;
this._queries = [];
this._curResults = undefined;
@@ -134,10 +136,15 @@ Client.prototype.connect = function(cfg) {
return self.emit('error', err);
cfg = clone(cfg);
cfg.host = address;
+ if (cfg.pingInterval)
+ self.pingInterval = cfg.pingInterval * 1000;
self._client.connect(cfg);
});
- } else
+ } else {
+ if (cfg.pingInterval)
+ self.pingInterval = cfg.pingInterval * 1000;
self._client.connect(cfg);
+ }
});
};
@@ -244,7 +251,13 @@ Client.prototype.prepare = function(query) {
return function() { return query; };
}
+Client.prototype._ping = function() {
+ self.query('DO 0', true, true);
+ this._pinger = setTimeout(this._ping, this.pingInterval);
+};
+
Client.prototype._reset = function() {
+ clearTimeout(this._pinger);
this._closeOnEmpty = false;
// TODO: do not empty queries if using an auto-reconnect algorithm
this._queries = [];
@@ -254,10 +267,13 @@ Client.prototype._reset = function() {
Client.prototype._processQueries = function() {
if (this._curResults === undefined && this.connected) {
if (this._queries.length) {
+ clearTimeout(this._pinger);
this._curResults = this._queries.shift();
this._client.query(this._curResults._query, this._curResults._useArray);
} else if (this._closeOnEmpty)
this.destroy();
+ else
+ this._pinger = setTimeout(this._ping, this.pingInterval);
}
};

0 comments on commit dca1aff

Please sign in to comment.