租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

248 lines
8.1 KiB

2 months ago
  1. # agentkeepalive
  2. [![NPM version][npm-image]][npm-url]
  3. [![build status][travis-image]][travis-url]
  4. [![Appveyor status][appveyor-image]][appveyor-url]
  5. [![Test coverage][codecov-image]][codecov-url]
  6. [![David deps][david-image]][david-url]
  7. [![Known Vulnerabilities][snyk-image]][snyk-url]
  8. [![npm download][download-image]][download-url]
  9. [npm-image]: https://img.shields.io/npm/v/agentkeepalive.svg?style=flat
  10. [npm-url]: https://npmjs.org/package/agentkeepalive
  11. [travis-image]: https://img.shields.io/travis/node-modules/agentkeepalive.svg?style=flat
  12. [travis-url]: https://travis-ci.org/node-modules/agentkeepalive
  13. [appveyor-image]: https://ci.appveyor.com/api/projects/status/k7ct4s47di6m5uy2?svg=true
  14. [appveyor-url]: https://ci.appveyor.com/project/fengmk2/agentkeepalive
  15. [codecov-image]: https://codecov.io/gh/node-modules/agentkeepalive/branch/master/graph/badge.svg
  16. [codecov-url]: https://codecov.io/gh/node-modules/agentkeepalive
  17. [david-image]: https://img.shields.io/david/node-modules/agentkeepalive.svg?style=flat
  18. [david-url]: https://david-dm.org/node-modules/agentkeepalive
  19. [snyk-image]: https://snyk.io/test/npm/agentkeepalive/badge.svg?style=flat-square
  20. [snyk-url]: https://snyk.io/test/npm/agentkeepalive
  21. [download-image]: https://img.shields.io/npm/dm/agentkeepalive.svg?style=flat-square
  22. [download-url]: https://npmjs.org/package/agentkeepalive
  23. The Node.js's missing `keep alive` `http.Agent`. Support `http` and `https`.
  24. ## What's different from original `http.Agent`?
  25. - `keepAlive=true` by default
  26. - Disable Nagle's algorithm: `socket.setNoDelay(true)`
  27. - Add free socket timeout: avoid long time inactivity socket leak in the free-sockets queue.
  28. - Add active socket timeout: avoid long time inactivity socket leak in the active-sockets queue.
  29. ## Install
  30. ```bash
  31. $ npm install agentkeepalive --save
  32. ```
  33. ## new Agent([options])
  34. * `options` {Object} Set of configurable options to set on the agent.
  35. Can have the following fields:
  36. * `keepAlive` {Boolean} Keep sockets around in a pool to be used by
  37. other requests in the future. Default = `true`.
  38. * `keepAliveMsecs` {Number} When using the keepAlive option, specifies the initial delay
  39. for TCP Keep-Alive packets. Ignored when the keepAlive option is false or undefined. Defaults to 1000.
  40. Default = `1000`. Only relevant if `keepAlive` is set to `true`.
  41. * `freeSocketKeepAliveTimeout`: {Number} Sets the free socket to timeout
  42. after `freeSocketKeepAliveTimeout` milliseconds of inactivity on the free socket.
  43. Default is `15000`.
  44. Only relevant if `keepAlive` is set to `true`.
  45. * `timeout`: {Number} Sets the working socket to timeout
  46. after `timeout` milliseconds of inactivity on the working socket.
  47. Default is `freeSocketKeepAliveTimeout * 2`.
  48. * `maxSockets` {Number} Maximum number of sockets to allow per
  49. host. Default = `Infinity`.
  50. * `maxFreeSockets` {Number} Maximum number of sockets (per host) to leave open
  51. in a free state. Only relevant if `keepAlive` is set to `true`.
  52. Default = `256`.
  53. * `socketActiveTTL` {Number} Sets the socket active time to live, even if it's in use.
  54. If not setted the behaviour continues the same (the socket will be released only when free)
  55. Default = `null`.
  56. ## Usage
  57. ```js
  58. const http = require('http');
  59. const Agent = require('agentkeepalive');
  60. const keepaliveAgent = new Agent({
  61. maxSockets: 100,
  62. maxFreeSockets: 10,
  63. timeout: 60000,
  64. freeSocketKeepAliveTimeout: 30000, // free socket keepalive for 30 seconds
  65. });
  66. const options = {
  67. host: 'cnodejs.org',
  68. port: 80,
  69. path: '/',
  70. method: 'GET',
  71. agent: keepaliveAgent,
  72. };
  73. const req = http.request(options, res => {
  74. console.log('STATUS: ' + res.statusCode);
  75. console.log('HEADERS: ' + JSON.stringify(res.headers));
  76. res.setEncoding('utf8');
  77. res.on('data', function (chunk) {
  78. console.log('BODY: ' + chunk);
  79. });
  80. });
  81. req.on('error', e => {
  82. console.log('problem with request: ' + e.message);
  83. });
  84. req.end();
  85. setTimeout(() => {
  86. if (keepaliveAgent.statusChanged) {
  87. console.log('[%s] agent status changed: %j', Date(), keepaliveAgent.getCurrentStatus());
  88. }
  89. }, 2000);
  90. ```
  91. ### `getter agent.statusChanged`
  92. counters have change or not after last checkpoint.
  93. ### `agent.getCurrentStatus()`
  94. `agent.getCurrentStatus()` will return a object to show the status of this agent:
  95. ```js
  96. {
  97. createSocketCount: 10,
  98. closeSocketCount: 5,
  99. timeoutSocketCount: 0,
  100. requestCount: 5,
  101. freeSockets: { 'localhost:57479:': 3 },
  102. sockets: { 'localhost:57479:': 5 },
  103. requests: {}
  104. }
  105. ```
  106. ### Support `https`
  107. ```js
  108. const https = require('https');
  109. const HttpsAgent = require('agentkeepalive').HttpsAgent;
  110. const keepaliveAgent = new HttpsAgent();
  111. // https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8
  112. const options = {
  113. host: 'www.google.com',
  114. port: 443,
  115. path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8',
  116. method: 'GET',
  117. agent: keepaliveAgent,
  118. };
  119. const req = https.request(options, res => {
  120. console.log('STATUS: ' + res.statusCode);
  121. console.log('HEADERS: ' + JSON.stringify(res.headers));
  122. res.setEncoding('utf8');
  123. res.on('data', chunk => {
  124. console.log('BODY: ' + chunk);
  125. });
  126. });
  127. req.on('error', e => {
  128. console.log('problem with request: ' + e.message);
  129. });
  130. req.end();
  131. setTimeout(() => {
  132. console.log('agent status: %j', keepaliveAgent.getCurrentStatus());
  133. }, 2000);
  134. ```
  135. ## [Benchmark](https://github.com/node-modules/agentkeepalive/tree/master/benchmark)
  136. run the benchmark:
  137. ```bash
  138. cd benchmark
  139. sh start.sh
  140. ```
  141. Intel(R) Core(TM)2 Duo CPU P8600 @ 2.40GHz
  142. node@v0.8.9
  143. 50 maxSockets, 60 concurrent, 1000 requests per concurrent, 5ms delay
  144. Keep alive agent (30 seconds):
  145. ```js
  146. Transactions: 60000 hits
  147. Availability: 100.00 %
  148. Elapsed time: 29.70 secs
  149. Data transferred: 14.88 MB
  150. Response time: 0.03 secs
  151. Transaction rate: 2020.20 trans/sec
  152. Throughput: 0.50 MB/sec
  153. Concurrency: 59.84
  154. Successful transactions: 60000
  155. Failed transactions: 0
  156. Longest transaction: 0.15
  157. Shortest transaction: 0.01
  158. ```
  159. Normal agent:
  160. ```js
  161. Transactions: 60000 hits
  162. Availability: 100.00 %
  163. Elapsed time: 46.53 secs
  164. Data transferred: 14.88 MB
  165. Response time: 0.05 secs
  166. Transaction rate: 1289.49 trans/sec
  167. Throughput: 0.32 MB/sec
  168. Concurrency: 59.81
  169. Successful transactions: 60000
  170. Failed transactions: 0
  171. Longest transaction: 0.45
  172. Shortest transaction: 0.00
  173. ```
  174. Socket created:
  175. ```
  176. [proxy.js:120000] keepalive, 50 created, 60000 requestFinished, 1200 req/socket, 0 requests, 0 sockets, 0 unusedSockets, 50 timeout
  177. {" <10ms":662," <15ms":17825," <20ms":20552," <30ms":17646," <40ms":2315," <50ms":567," <100ms":377," <150ms":56," <200ms":0," >=200ms+":0}
  178. ----------------------------------------------------------------
  179. [proxy.js:120000] normal , 53866 created, 84260 requestFinished, 1.56 req/socket, 0 requests, 0 sockets
  180. {" <10ms":75," <15ms":1112," <20ms":10947," <30ms":32130," <40ms":8228," <50ms":3002," <100ms":4274," <150ms":181," <200ms":18," >=200ms+":33}
  181. ```
  182. ## License
  183. ```
  184. (The MIT License)
  185. Copyright(c) node-modules and other contributors.
  186. Copyright(c) 2012 - 2015 fengmk2 <fengmk2@gmail.com>
  187. Permission is hereby granted, free of charge, to any person obtaining
  188. a copy of this software and associated documentation files (the
  189. 'Software'), to deal in the Software without restriction, including
  190. without limitation the rights to use, copy, modify, merge, publish,
  191. distribute, sublicense, and/or sell copies of the Software, and to
  192. permit persons to whom the Software is furnished to do so, subject to
  193. the following conditions:
  194. The above copyright notice and this permission notice shall be
  195. included in all copies or substantial portions of the Software.
  196. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  197. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  198. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  199. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  200. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  201. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  202. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  203. ```