微服务使用JS脚本实现,支持模块化管理、高并发访问、数据库访问,主要用于扩展后端服务,或者创建其他独立的业务逻辑。 可用于实现移动端和服务端访问请求,以及通用的业务处理和数据查询服务,一个视频看懂微服务。点击这里查看实战demo。架构图如下所示:
// 调用接口call_demo,参数分别为'name'和123,返回值为ret function main() { var ret = callMicroService('call_demo', ['name', 123]); console.log('ret:' + ret); }
// 接口call_demo对应的脚本, name和value为移动端传入的参数 function main(name = '', value = 1) { console.log('name:' + name + ' value:' + value); return name + value; }
// 调用服务端接口call_demo,参数为['name', 123],clientKey和accessToken请替换成自己的鉴权参数 https://aznfz.com/api/call_micro_service?clientKey=xxxxx&accessToken=yyyyy&name=call_demo&isDev=true& params=%5B'name'%2C%20123%5D
// 接口call_demo对应的脚本, name和value为移动端传入的参数 function main(name = '', value = 1) { console.log('name:' + name + ' value:' + value); return name + value; }
业务参数元数据: [{"name":"param","id":"p","type":"int","defaultValue":12,"description":"测试"}] // 业务对应的脚本如下:(注意,函数参数必须与业务参数一致) function main(p=1) { console.log('param:' + p); var users = userList(); console.log('users:' + users); for (var u of users) { console.log('u:' + u); var devices = deviceList(u.openId); console.log('用户:' + u.username + ' 设备:' + devices); } // 获取管理员的设备 var devices = deviceList(''); console.log('管理员设备:' + devices); }
/* [{ "id": 1, "name": "a", "value": "postman" }, { "id": 2, "name": "ab", "value": "freeman" }, { "id": 3, "name": "b", "value": "policeman" }, { "id": 4, "name": "c", "value": "bad guy" }] */ // 用于获取需要显示的表格数据,查询脚本的参数必须是如下格式:fetchCountOnly表示是否仅获取数据总数,conditions表示json数组格式的查询条件,startIndex表示游标值,itemCount表示一页的最大个数 function main(fetchCountOnly, conditions, startIndex, itemCount) { var jsonConditions = JSON.parse(conditions); var data = JSON.parse(getCustomData('query_data')); var ret = data; if (jsonConditions && jsonConditions.length > 0) { ret = []; for (var item of jsonConditions) { if (item.name == 'name') { for (var d of data) { if (d.name.includes(item.value)) { ret.push(d); } } } } } if (fetchCountOnly) { // 返回符合条件的数据个数 return ret.length; } else { // 返回符合条件的格式化数据 return ret; } } // 删除数据操作脚本, 脚本的参数必须如下所示,item表示选中后将要操作的数据项 function deleteItem(item) { var data = JSON.parse(getCustomData('query_data')); var index = 0; for (var d of data) { if (d.id == item.id) { break; } ++index; } data.splice(index, 1); return setCustomData('query_data', data + ''); }
// url、minInterval,maxInterval为业务处理服务透传过来的参数 function main(url, minInterval, maxInterval) { var devices = deviceList(); for (var device of devices) { // 仅调度在线手机 if (device.onlineState == 1) { // 在手机上执行移动端名为"test"的脚本,这里的url参数会直接透传给移动端脚本的main函数参数。 scriptExe('test', device.uuid, [url], true); // 在minInterval和maxInterval之间随机延时一段时间 sleep(Math.random() * (maxInterval - minInterval) + minInterval); } } }
// url参数的值,是上面的微服务脚本通过调用scriptExe函数透传过来的。 function main(url) { console.log('url:' + url); }