web_worker_rpc
一个安全,易用的web worker rpc脚本
description
web_worker_rpc,提供宿主与worker通信的RPC能力,并保证了以下情况时宿主的安全性1. worker死循环或者任何超出了worker负荷能力 # CONFIG.HEARTBEAT2. worker讳规过于频繁地向宿主发生请求 # CONFIG.QPS3. worker内部错误达到限制数量 # CONFIG.ONERROR_LIMIT4. 单次完成任务时间过长 # CONFIG.TIMEOUT
example
install
npm install web_worker_rpc
or
yarn add web_worker_rpc
usage
- import it in script tag.
- RPC in your host.js
// host.jsconst rpc = window'__web_worker_rpc'// 创建一个新的worker// 第一参数传入 url// 第二参数转入需要暴露给worker的方法let worker = rpc
// host.js// 调用worker的方法workerremote
// host.js// 销毁worker;
- RPC in worker.js, you can call host api remotely.
// 远程提供给host方法rpcexports = { return 'from worker'; }
// 远程调用host方法rpcremote;// 所有远端方法都是 promiselet r = await rpcremoteothers_api;
// you can even RPC with callback function!let canceller = rpcremote// removeListener
configuration
谨慎修改配置
// how long is a remote call timeout, // default 42000, 42 sec TIMEOUT: number; // heartbeat to detect if worker is still alive, // default 4200, 4.2 sec HEARTBEAT: number; // requested limit per second, when reach, the worker restart, // default 1000, worker can request at most 1000 times in a second QPS: number; // when errors counter reached, the worker restart, // default 64 ONERROR_LIMIT: number; ;
// in <host.js>const rpc = window'__web_worker_rpc'rpcCONFIGTIMEOUT = 22;// 设置调用 host API超时为22ms, 抛出超时异常 // in <worker.js>// no need to declare rpc, internalrpcTIMEOUT = 22;// 设置调用超时22ms, 抛出超时异常
FAQ
当worker发生异常时,如何处理
worker将自动关闭,你可以获得异常和关闭的事件,
worker{ console;}
你也可以将它重启,简单地,重新create一个
worker{ console; rpc}