当前位置: 首页 > SEO学院网络营销

小程序·云开发的云函数路由高级玩法,腾讯云函数官网

来源:未知 浏览量:94次
李成熙腾讯云高级工程师。2014年度毕业加入腾讯AlloyTeam先后负责过QQ群、花样直播、腾讯文档等项目。2018年加入腾讯云云开发团队。专注于性能优化、工程化和小程序服务。微博 | 知乎 | Github 概念回顾

在掘金开发者大会上网络营销手段先后负责过QQ群、花样直播、腾讯文档等项目。2018年加入腾讯云云开发团队。专注于性能优化、工程化和小程序服务。微博 | 知乎 | Github 概念回顾

在掘金开发者大会上在推荐实践那里我有提到一种云函数的用法我们可以将相同的一些操作比如用户管理、支付逻辑按照业务的相似性归类到一个云函数里这样比较方便管理、排查问题以及逻辑的共享。甚至如果你的小程序的后台逻辑不复杂请求量不是特别大完全可以在云函数里面做一个单一的微服务根据路由来处理任务。

用下面三幅图可以概括我们来回顾一下:

小程序·云开发的云函数路由高级玩法

小程序·云开发的云函数路由高级玩法

比如这里就是传统的云函数用法一个云函数处理一个任务高度解耦。

第二幅架构图就是尝试将请求归类一个云函数处理某一类的请求比如有专门负责处理用户的或者专门处理支付的云函数。

最后一幅图显示这里只有一个云函数云函数里有一个分派任务的路由管理将不同的任务分配给不同的本地函数处理。

tcb-router 介绍及用法

为了方便大家试用咱们腾讯云 Tencent Cloud Base 团队开发了 tcb-router云函数路由管理库方便大家使用。

那具体怎么使用 tcb-router 去实现上面提到的架构呢?下面我会逐一举例子。

架构一:一个云函数处理一个任务
这种架构下其实不需要用到 tcb-router像普通那样写好云函数企业品牌策划像普通那样写好云函数然后在小程序端调用就可以了。

云函数

// 函数 router exports.main = (event, context) => { return { code: 0, message: 'success' }; }; 小程序端 wx.cloud.callFunction({ name: 'router', data: { name: 'tcb', company: 'Tencent' } }).then((res) => { console.log(res); }).catch((e) => { console.log(e); });
 

架构二: 按请求给云函数归类
此类架构就是将相似的请求归类到同一个云函数处理比如可以分为用户管理、支付等等的云函数。

云函数

// 函数 pay const TcbRouter = require('tcb-router'); exports.main = async (event, context) => { const app = new TcbRouter({ event }); app.router('makeOrder', async (ctx, next) => { await next(); }, async (ctx, next) => { await next(); }, async (ctx) => { ctx.body = { code: 0, message: 'make order success' } }); app.router('pay', async (ctx, next) => { await next(); }, async (ctx, next) => { await next(); }, async (ctx) => { ctx.body = { code: 0, message: 'pay success' } }); return app.serve(); };  

小程序端

// 注册用户 wx.cloud.callFunction({ name: 'user', data: { $url: 'register', name: 'tcb', password: '09876' } }).then((res) => { console.log(res); }).catch((e) => { console.log(e); }); // 下单商品 wx.cloud.callFunction({ name: 'pay', data: { $url: 'makeOrder', id: 'xxxx', amount: '3' } }).then((res) => { console.log(res); }).catch((e) => { console.log(e); });  

架构三: 由一个云函数处理所有服务

// 函数 router const TcbRouter = require('tcb-router'); exports.main = async (event, context) => { const app = new TcbRouter({ event }); app.router('user/register', async (ctx, next) => { await next(); }, async (ctx, next) => { await next(); }, async (ctx) => { ctx.body = { code: 0, message: 'register success' } }); app.router('user/login', async (ctx, next) => { await next(); }, async (ctx, next) => { await next(); }, async (ctx) => { ctx.body = { code: 0, message: 'login success' } }); app.router('pay/makeOrder', async (ctx, next) => { await next(); }, async (ctx, next) => { await next(); }, async (ctx) => { ctx.body = { code: 0, message: 'make order success' } }); app.router('pay/pay', async (ctx, next) => { await next(); }, async (ctx, next) => { await next(); }, async (ctx) => { ctx.body = { code: 0, message: 'pay success' } }); return app.serve(); };  

展开全部内容