├── .gitignore ├── .jsbeautifyrc ├── README.md ├── api-all.js ├── api.js ├── app-all.js ├── book-store-service.js ├── book-store-stats.js ├── book-store-test.js ├── book-store.js ├── book.js ├── hapi-app-client.js ├── hapi-app.js ├── math-client-tcp.js ├── math-client.js ├── math-pin-client.js ├── math-pin-service.js ├── math-plugin-init.js ├── math-plugin.js ├── math-service-tcp.js ├── math-service.js ├── math-tree.js ├── math.js ├── math.log ├── minimal-plugin.js ├── package.json ├── pattern-priority-testing.js ├── product.js ├── sum-integer.js ├── sum-product.js ├── sum-reuse.js ├── sum-valid.js └── sum.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.jsbeautifyrc: -------------------------------------------------------------------------------- 1 | { 2 | "html": { 3 | "allowed_file_extensions": [html", "xml", "svg"], 4 | "brace_style": "collapse", 5 | "end_with_newline": false, 6 | "indent_char": " ", 7 | "indent_handlebars": false, 8 | "indent_inner_html": false, 9 | "indent_scripts": "keep", 10 | "indent_size": 2, 11 | "max_preserve_newlines": 0, 12 | "preserve_newlines": true, 13 | "wrap_line_length": 0 14 | }, 15 | "css": { 16 | "allowed_file_extensions": ["css", "scss", "sass", "less", "styl"], 17 | "end_with_newline": false, 18 | "indent_char": " ", 19 | "indent_size": 2, 20 | "newline_between_rules": true, 21 | "selector_separator": " ", 22 | "selector_separator_newline": true 23 | }, 24 | "js": { 25 | "allowed_file_extensions": ["js", "json"], 26 | "brace_style": "collapse", 27 | "break_chained_methods": false, 28 | "indent_char": " ", 29 | "indent_level": 0, 30 | "indent_size": 2, 31 | "indent_with_tabs": false, 32 | "keep_array_indentation": false, 33 | "keep_function_indentation": false, 34 | "max_preserve_newlines": 0, 35 | "preserve_newlines": true, 36 | "space_after_anon_function": false, 37 | "space_before_conditional": true, 38 | "space_in_empty_paren": false, 39 | "space_in_paren": false, 40 | "unescape_strings": false, 41 | "wrap_line_length": 0 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Seneca :NodeJS 微服务框架入门指南 2 | 3 | [Seneca](http://senecajs.org/) 是一个能让您快速构建基于消息的微服务系统的工具集,你不需要知道各种服务本身被部署在何处,不需要知道具体有多少服务存在,也不需要知道他们具体做什么,任何你业务逻辑之外的服务(如数据库、缓存或者第三方集成等)都被隐藏在微服务之后。 4 | 5 | 这种解耦使您的系统易于连续构建与更新,Seneca 能做到这些,原因在于它的三大核心功能: 6 | 7 | 1. **模式匹配**:不同于脆弱的服务发现,模式匹配旨在告诉这个世界你真正关心的消息是什么; 8 | 2. **无依赖传输**:你可以以多种方式在服务之间发送消息,所有这些都隐藏至你的业务逻辑之后; 9 | 3. **组件化**:功能被表示为一组可以一起组成微服务的插件。 10 | 11 | 在 Seneca 中,消息就是一个可以有任何你喜欢的内部结构的 `JSON` 对象,它们可以通过 HTTP/HTTPS、TCP、消息队列、发布/订阅服务或者任何能传输数据的方式进行传输,而对于作为消息生产者的你来讲,你只需要将消息发送出去即可,完全不需要关心哪些服务来接收它们。 12 | 13 | 然后,你又想告诉这个世界,你想要接收一些消息,这也很简单,你只需在 Seneca 中作一点匹配模式配置即可,匹配模式也很简单,只是一个键值对的列表,这些键值对被用于匹配 `JSON` 消息的极组属性。 14 | 15 | 在本文接下来的内容中,我们将一同基于 Seneca 构建一些微服务。 16 | 17 | # 模式( _Patterns_ ) 18 | 19 | 让我们从一点特别简单的代码开始,我们将创建两个微服务,一个会进行数学计算,另一个去调用它: 20 | 21 | ```javascript 22 | const seneca = require('seneca')(); 23 | 24 | seneca.add('role:math, cmd:sum', (msg, reply) => { 25 | reply(null, { answer: ( msg.left + msg.right )}) 26 | }); 27 | 28 | seneca.act({ 29 | role: 'math', 30 | cmd: 'sum', 31 | left: 1, 32 | right: 2 33 | }, (err, result) => { 34 | if (err) { 35 | return console.error(err); 36 | } 37 | console.log(result); 38 | }); 39 | ``` 40 | 41 | 将上面的代码,保存至一个 `js` 文件中,然后执行它,你可能会在 `console` 中看到类似下面这样的消息: 42 | 43 | ```bash 44 | {"kind":"notice","notice":"hello seneca 4y8daxnikuxp/1483577040151/58922/3.2.2/-","level":"info","when":1483577040175} 45 | (node:58922) DeprecationWarning: 'root' is deprecated, use 'global' 46 | { answer: 3 } 47 | ``` 48 | 49 | 到目前为止,所有这一切都发生在同一个进程中,没有网络流量产生,进程内的函数调用也是基于消息传输。 50 | 51 | `seneca.add` 方法,添加了一个新的动作模式(_Action Pattern_)至 `Seneca` 实例中,它有两个参数: 52 | 53 | 1. `pattern` :用于匹配 Seneca 实例中 `JSON` 消息体的模式; 54 | 2. `action` :当模式被匹配时执行的操作 55 | 56 | `seneca.act` 方法同样有两个参数: 57 | 58 | 1. `msg` :作为纯对象提供的待匹配的入站消息; 59 | 2. `respond` :用于接收并处理响应信息的回调函数。 60 | 61 | 让我们再把所有代码重新过一次: 62 | 63 | ```javascript 64 | seneca.add('role:math, cmd:sum', (msg, reply) => { 65 | reply(null, { answer: ( msg.left + msg.right )}) 66 | }); 67 | ``` 68 | 69 | 在上面的代码中的 `Action` 函数,计算了匹配到的消息体中两个属性 `left` 与 `right` 的值的和,并不是所有的消息都会被创建一个响应,但是在绝大多数情况下,是需要有响应的, Seneca 提供了用于响应消息的回调函数。 70 | 71 | 在匹配模式中, `role:math, cmd:sum` 匹配到了下面这个消息体: 72 | 73 | ```javascript 74 | { 75 | role: 'math', 76 | cmd: 'sum', 77 | left: 1, 78 | right: 2 79 | } 80 | ``` 81 | 82 | 并得到计自结果: 83 | 84 | ```javascript 85 | { 86 | answer: 3 87 | } 88 | ``` 89 | 90 | 关于 `role` 与 `cmd` 这两个属性,它们没有什么特别的,只是恰好被你用于匹配模式而已。 91 | 92 | 接着,`seneca.act` 方法,发送了一条消息,它有两个参数: 93 | 94 | 1. `msg` :发送的消息主体 95 | 2. `response_callback` :如果该消息有任何响应,该回调函数都会被执行。 96 | 97 | 响应的回调函数可接收两个参数: `error` 与 `result` ,如果有任何错误发生(比如,发送出去的消息未被任何模式匹配),则第一个参数将是一个 `Error` 对象,而如果程序按照我们所预期的方向执行了的话,那么,第二个参数将接收到响应结果,在我们的示例中,我们只是简单的将接收到的响应结果打印至了 `console` 而已。 98 | 99 | ```javascript 100 | seneca.act({ 101 | role: 'math', 102 | cmd: 'sum', 103 | left: 1, 104 | right: 2 105 | }, (err, result) => { 106 | if (err) { 107 | return console.error(err); 108 | } 109 | console.log(result); 110 | }); 111 | ``` 112 | 113 | [sum.js](https://github.com/pantao/getting-started-seneca/blob/master/sum.js) 示例文件,向你展示了如何定义并创建一个 Action 以及如何呼起一个 Action,但它们都发生在一个进程中,接下来,我们很快就会展示如何拆分成不同的代码和多个进程。 114 | 115 | # 匹配模式如何工作? 116 | 117 | 模式----而不是网络地址或者会话,让你可以更加容易的扩展或增强您的系统,这样做,让添加新的微服务变得更简单。 118 | 119 | 现在让我们给系统再添加一个新的功能----计算两个数字的乘积。 120 | 121 | 我们想要发送的消息看起来像下面这样的: 122 | 123 | ```javascript 124 | { 125 | role: 'math', 126 | cmd: 'product', 127 | left: 3, 128 | right: 4 129 | } 130 | ``` 131 | 132 | 而后获得的结果看起来像下面这样的: 133 | 134 | ```javascript 135 | { 136 | answer: 12 137 | } 138 | ``` 139 | 140 | 知道怎么做了吧?你可以像 `role: math, cmd: sum` 模式这样,创建一个 `role: math, cmd: product` 操作: 141 | 142 | ```javascript 143 | seneca.add('role:math, cmd:product', (msg, reply) => { 144 | reply(null, { answer: ( msg.left * msg.right )}) 145 | }); 146 | ``` 147 | 148 | 然后,调用该操作: 149 | 150 | ```javascript 151 | seneca.act({ 152 | role: 'math', 153 | cmd: 'product', 154 | left: 3, 155 | right: 4 156 | }, (err, result) => { 157 | if (err) { 158 | return console.error(err); 159 | } 160 | console.log(result); 161 | }); 162 | ``` 163 | 164 | 运行 [product.js](https://github.com/pantao/getting-started-seneca/blob/master/product.js) ,你将得到你想要的结果。 165 | 166 | 将这两个方法放在一起,代码像是下面这样的: 167 | 168 | ```javascript 169 | const seneca = require('seneca')(); 170 | 171 | seneca.add('role:math, cmd:sum', (msg, reply) => { 172 | reply(null, { answer: ( msg.left + msg.right )}) 173 | }); 174 | 175 | seneca.add('role:math, cmd:product', (msg, reply) => { 176 | reply(null, { answer: ( msg.left * msg.right )}) 177 | }); 178 | 179 | seneca.act({role: 'math', cmd: 'sum', left: 1, right: 2}, console.log) 180 | .act({role: 'math', cmd: 'product', left: 3, right: 4}, console.log) 181 | ``` 182 | 183 | 运行 [sum-product.js](https://github.com/pantao/getting-started-seneca/blob/master/sum-product.js) 后,你将得到下面这样的结果: 184 | 185 | ```bash 186 | null { answer: 3 } 187 | null { answer: 12 } 188 | ``` 189 | 190 | 在上面合并到一起的代码中,我们发现, `seneca.act` 是可以进行链式调用的,`Seneca` 提供了一个链式API,调式调用是顺序执行的,但是不是串行,所以,返回的结果的顺序可能与调用顺序并不一样。 191 | 192 | # 扩展模式以增加新功能 193 | 194 | 模式让你可以更加容易的扩展程序的功能,与 `if...else...` 语法不同的是,你可以通过增加更多的匹配模式以达到同样的功能。 195 | 196 | 下面让我们扩展一下 `role: math, cmd: sum` 操作,它只接收整型数字,那么,怎么做? 197 | 198 | ```javascript 199 | seneca.add({role: 'math', cmd: 'sum', integer: true}, function (msg, respond) { 200 | var sum = Math.floor(msg.left) + Math.floor(msg.right) 201 | respond(null, {answer: sum}) 202 | }) 203 | ``` 204 | 205 | 现在,下面这条消息: 206 | 207 | ```javascript 208 | {role: 'math', cmd: 'sum', left: 1.5, right: 2.5, integer: true} 209 | ``` 210 | 211 | 将得到下面这样的结果: 212 | 213 | ```javascript 214 | {answer: 3} // == 1 + 2,小数部分已经被移除了 215 | ``` 216 | 217 | 代码可在 [sum-integer.js](https://github.com/pantao/getting-started-seneca/blob/master/sum-integer.js) 中查看。 218 | 219 | 现在,你的两个模式都存在于系统中了,而且还存在交叉部分,那么 `Seneca` 最终会将消息匹配至哪条模式呢?原则是:更多匹配项目被匹配到的优先,被匹配到的属性越多,则优先级越高。 220 | 221 | [pattern-priority-testing.js](https://github.com/pantao/getting-started-seneca/blob/master/pattern-priority-testing.js) 可以给我们更加直观的测试: 222 | 223 | ```javascript 224 | const seneca = require('seneca')() 225 | 226 | seneca.add({role: 'math', cmd: 'sum'}, function (msg, respond) { 227 | var sum = msg.left + msg.right 228 | respond(null, {answer: sum}) 229 | }) 230 | 231 | // 下面两条消息都匹配 role: math, cmd: sum 232 | 233 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5}, console.log) 234 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5, integer: true}, console.log) 235 | 236 | setTimeout(() => { 237 | seneca.add({role: 'math', cmd: 'sum', integer: true}, function (msg, respond) { 238 | var sum = Math.floor(msg.left) + Math.floor(msg.right) 239 | respond(null, { answer: sum }) 240 | }) 241 | 242 | // 下面这条消息同样匹配 role: math, cmd: sum 243 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5}, console.log) 244 | 245 | // 但是,也匹配 role:math,cmd:sum,integer:true 246 | // 但是因为更多属性被匹配到,所以,它的优先级更高 247 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5, integer: true}, console.log) 248 | }, 100) 249 | ``` 250 | 251 | 输出结果应该像下面这样: 252 | 253 | ```bash 254 | null { answer: 4 } 255 | null { answer: 4 } 256 | null { answer: 4 } 257 | null { answer: 3 } 258 | ``` 259 | 260 | 在上面的代码中,因为系统中只存在 `role: math, cmd: sum` 模式,所以,都匹配到它,但是当 100ms 后,我们给系统中添加了一个 `role: math, cmd: sum, integer: true` 模式之后,结果就不一样了,匹配到更多的操作将有更高的优先级。 261 | 262 | 这种设计,可以让我们的系统可以更加简单的添加新的功能,不管是在开发环境还是在生产环境中,你都可以在不需要修改现有代码的前提下即可更新新的服务,你只需要先好新的服务,然后启动新服务即可。 263 | 264 | # 基于模式的代码复用 265 | 266 | 模式操作还可以调用其它的操作,所以,这样我们可以达到代码复用的需求: 267 | 268 | ```javascript 269 | const seneca = require('seneca')() 270 | 271 | seneca.add('role: math, cmd: sum', function (msg, respond) { 272 | var sum = msg.left + msg.right 273 | respond(null, {answer: sum}) 274 | }) 275 | 276 | seneca.add('role: math, cmd: sum, integer: true', function (msg, respond) { 277 | // 复用 role:math, cmd:sum 278 | this.act({ 279 | role: 'math', 280 | cmd: 'sum', 281 | left: Math.floor(msg.left), 282 | right: Math.floor(msg.right) 283 | }, respond) 284 | }) 285 | 286 | // 匹配 role:math,cmd:sum 287 | seneca.act('role: math, cmd: sum, left: 1.5, right: 2.5',console.log) 288 | 289 | // 匹配 role:math,cmd:sum,integer:true 290 | seneca.act('role: math, cmd: sum, left: 1.5, right: 2.5, integer: true', console.log) 291 | ``` 292 | 293 | 在上面的示例代码中,我们使用了 `this.act` 而不是前面的 `seneca.act`,那是因为,在 `action` 函数中,上下文关系变量 `this` ,引用了当前的 `seneca` 实例,这样你就可以在任何一个 `action` 函数中,访问到该 `action` 调用的整个上下文。 294 | 295 | 在上面的代码中,我们使用了 JSON 缩写形式来描述模式与消息, 比如,下面是对象字面量: 296 | 297 | ```javascript 298 | {role: 'math', cmd: 'sum', left: 1.5, right: 2.5} 299 | ``` 300 | 301 | 缩写模式为: 302 | 303 | ```text 304 | 'role: math, cmd: sum, left: 1.5, right: 2.5' 305 | ``` 306 | 307 | [jsonic](https://github.com/rjrodger/jsonic) 这种格式,提供了一种以字符串字面量来表达对象的简便方式,这使得我们可以创建更加简单的模式和消息。 308 | 309 | 上面的代码保存在了 [sum-reuse.js](https://github.com/pantao/getting-started-seneca/blob/master/sum-reuse.js) 文件中。 310 | 311 | # 模式是唯一的 312 | 313 | 你定义的 Action 模式都是唯一了,它们只能触发一个函数,模式的解析规则如下: 314 | 315 | - 更多我属性优先级更高 316 | - 若模式具有相同的数量的属性,则按字母顺序匹配 317 | 318 | 规则被设计得很简单,这使得你可以更加简单的了解到到底是哪个模式被匹配了。 319 | 320 | 下面这些示例可以让你更容易理解: 321 | 322 | - `a: 1, b: 2` 优先于 `a: 1`, 因为它有更多的属性; 323 | - `a: 1, b: 2` 优先于 `a: 1, c: 3`,因为 `b` 在 `c` 字母的前面; 324 | - `a: 1, b: 2, d: 4` 优先于 `a: 1, c: 3, d:4`,因为 `b` 在 `c` 字母的前面; 325 | - `a: 1, b:2, c:3` 优先于 `a:1, b: 2`,因为它有更多的属性; 326 | - `a: 1, b:2, c:3` 优先于 `a:1, c:3`,因为它有更多的属性。 327 | 328 | 很多时间,提供一种可以让你不需要全盘修改现有 Action 函数的代码即可增加它功能的方法是很有必要的,比如,你可能想为某一个消息增加更多自定义的属性验证方法,捕获消息统计信息,添加额外的数据库结果中,或者控制消息流速等。 329 | 330 | 我下面的示例代码中,加法操作期望 `left` 和 `right` 属性是有限数,此外,为了调试目的,将原始输入参数附加到输出的结果中也是很有用的,您可以使用以下代码添加验证检查和调试信息: 331 | 332 | ```javascript 333 | const seneca = require('seneca')() 334 | 335 | seneca 336 | .add( 337 | 'role:math,cmd:sum', 338 | function(msg, respond) { 339 | var sum = msg.left + msg.right 340 | respond(null, { 341 | answer: sum 342 | }) 343 | }) 344 | 345 | // 重写 role:math,cmd:sum with ,添加额外的功能 346 | .add( 347 | 'role:math,cmd:sum', 348 | function(msg, respond) { 349 | 350 | // bail out early if there's a problem 351 | if (!Number.isFinite(msg.left) || 352 | !Number.isFinite(msg.right)) { 353 | return respond(new Error("left 与 right 值必须为数字。")) 354 | } 355 | 356 | // 调用上一个操作函数 role:math,cmd:sum 357 | this.prior({ 358 | role: 'math', 359 | cmd: 'sum', 360 | left: msg.left, 361 | right: msg.right, 362 | 363 | }, function(err, result) { 364 | if (err) return respond(err) 365 | 366 | result.info = msg.left + '+' + msg.right 367 | respond(null, result) 368 | }) 369 | }) 370 | 371 | // 增加了的 role:math,cmd:sum 372 | .act('role:math,cmd:sum,left:1.5,right:2.5', 373 | console.log // 打印 { answer: 4, info: '1.5+2.5' } 374 | ) 375 | ``` 376 | 377 | `seneca` 实例提供了一个名为 `prior` 的方法,让可以在当前的 `action` 方法中,调用被其重写的旧操作函数。 378 | 379 | `prior` 函数接受两个参数: 380 | 381 | 1. `msg`:消息体 382 | 2. `response_callback`:回调函数 383 | 384 | 在上面的示例代码中,已经演示了如何修改入参与出参,修改这些参数与值是可选的,比如,可以再添加新的重写,以增加日志记录功能。 385 | 386 | 在上面的示例中,也同样演示了如何更好的进行错误处理,我们在真正进行操作之前,就验证的数据的正确性,若传入的参数本身就有错误,那么我们直接就返回错误信息,而不需要等待真正计算的时候由系统去报错了。 387 | 388 | > 错误消息应该只被用于描述错误的输入或者内部失败信息等,比如,如果你执行了一些数据库的查询,返回没有任何数据,这并不是一个错误,而仅仅只是数据库的事实的反馈,但是如果连接数据库失败,那就是一个错误了。 389 | 390 | 上面的代码可以在 [sum-valid.js](https://github.com/pantao/getting-started-seneca/blob/master/sum-valid.js) 文件中找到。 391 | 392 | # 使用插件组织模式 393 | 394 | 一个 `seneca` 实例,其实就只是多个 `Action Patterm` 的集合而已,你可以使用命名空间的方式来组织操作模式,例如在前面的示例中,我们都使用了 `role: math`,为了帮助日志记录和调试, `Seneca` 还支持一个简约的插件支持。 395 | 396 | 同样,Seneca插件只是一组操作模式的集合,它可以有一个名称,用于注释日志记录条目,还可以给插件一组选项来控制它们的行为,插件还提供了以正确的顺序执行初始化函数的机制,例如,您希望在尝试从数据库读取数据之前建立数据库连接。 397 | 398 | 简单来说,Seneca插件就只是一个具有单个参数选项的函数,你将这个插件定义函数传递给 `seneca.use` 方法,下面这个是最小的Seneca插件(其实它什么也没做!): 399 | 400 | ```javascript 401 | function minimal_plugin(options) { 402 | console.log(options) 403 | } 404 | 405 | require('seneca')() 406 | .use(minimal_plugin, {foo: 'bar'}) 407 | ``` 408 | 409 | `seneca.use` 方法接受两个参数: 410 | 411 | 1. `plugin` :插件定义函数或者一个插件名称; 412 | 2. `options` :插件配置选项 413 | 414 | 上面的示例代码执行后,打印出来的日志看上去是这样的: 415 | 416 | ```bash 417 | {"kind":"notice","notice":"hello seneca 3qk0ij5t2bta/1483584697034/62768/3.2.2/-","level":"info","when":1483584697057} 418 | (node:62768) DeprecationWarning: 'root' is deprecated, use 'global' 419 | { foo: 'bar' } 420 | ``` 421 | 422 | Seneca 还提供了详细日志记录功能,可以提供为开发或者生产提供更多的日志信息,通常的,日志级别被设置为 `INFO`,它并不会打印太多日志信息,如果想看到所有的日志信息,试试以下面这样的方式启动你的服务: 423 | 424 | ```bash 425 | node minimal-plugin.js --seneca.log.all 426 | ``` 427 | 428 | 会不会被吓一跳?当然,你还可以过滤日志信息: 429 | 430 | ```bash 431 | node minimal-plugin.js --seneca.log.all | grep plugin:define 432 | ``` 433 | 434 | 通过日志我们可以看到, seneca 加载了很多内置的插件,比如 `basic`、`transport`、`web` 以及 `mem-store`,这些插件为我们提供了创建微服务的基础功能,同样,你应该也可以看到 `minimal_plugin` 插件。 435 | 436 | 现在,让我们为这个插件添加一些操作模式: 437 | 438 | ```javascript 439 | function math(options) { 440 | 441 | this.add('role:math,cmd:sum', function (msg, respond) { 442 | respond(null, { answer: msg.left + msg.right }) 443 | }) 444 | 445 | this.add('role:math,cmd:product', function (msg, respond) { 446 | respond(null, { answer: msg.left * msg.right }) 447 | }) 448 | 449 | } 450 | 451 | require('seneca')() 452 | .use(math) 453 | .act('role:math,cmd:sum,left:1,right:2', console.log) 454 | ``` 455 | 456 | 运行 [math-plugin.js](https://github.com/pantao/getting-started-seneca/blob/master/math-plugin.js) 文件,得到下面这样的信息: 457 | 458 | ```bash 459 | null { answer: 3 } 460 | ``` 461 | 462 | 看打印出来的一条日志: 463 | 464 | ```javascript 465 | { 466 | "actid": "7ubgm65mcnfl/uatuklury90r", 467 | "msg": { 468 | "role": "math", 469 | "cmd": "sum", 470 | "left": 1, 471 | "right": 2, 472 | "meta$": { 473 | "id": "7ubgm65mcnfl/uatuklury90r", 474 | "tx": "uatuklury90r", 475 | "pattern": "cmd:sum,role:math", 476 | "action": "(bjx5u38uwyse)", 477 | "plugin_name": "math", 478 | "plugin_tag": "-", 479 | "prior": { 480 | "chain": [], 481 | "entry": true, 482 | "depth": 0 483 | }, 484 | "start": 1483587274794, 485 | "sync": true 486 | }, 487 | "plugin$": { 488 | "name": "math", 489 | "tag": "-" 490 | }, 491 | "tx$": "uatuklury90r" 492 | }, 493 | "entry": true, 494 | "prior": [], 495 | "meta": { 496 | "plugin_name": "math", 497 | "plugin_tag": "-", 498 | "plugin_fullname": "math", 499 | "raw": { 500 | "role": "math", 501 | "cmd": "sum" 502 | }, 503 | "sub": false, 504 | "client": false, 505 | "args": { 506 | "role": "math", 507 | "cmd": "sum" 508 | }, 509 | "rules": {}, 510 | "id": "(bjx5u38uwyse)", 511 | "pattern": "cmd:sum,role:math", 512 | "msgcanon": { 513 | "cmd": "sum", 514 | "role": "math" 515 | }, 516 | "priorpath": "" 517 | }, 518 | "client": false, 519 | "listen": false, 520 | "transport": {}, 521 | "kind": "act", 522 | "case": "OUT", 523 | "duration": 35, 524 | "result": { 525 | "answer": 3 526 | }, 527 | "level": "debug", 528 | "plugin_name": "math", 529 | "plugin_tag": "-", 530 | "pattern": "cmd:sum,role:math", 531 | "when": 1483587274829 532 | } 533 | ``` 534 | 535 | 所有的该插件的日志都被自动的添加了 `plugin` 属性。 536 | 537 | 在 Seneca 的世界中,我们通过插件组织各种操作模式集合,这让日志与调试变得更简单,然后你还可以将多个插件合并成为各种微服务,在接下来的章节中,我们将创建一个 `math` 服务。 538 | 539 | 插件通过需要进行一些初始化的工作,比如连接数据库等,但是,你并不需要在插件的定义函数中去执行这些初始化,定义函数被设计为同步执行的,因为它的所有操作都是在定义一个插件,事实上,你不应该在定义函数中调用 `seneca.act` 方法,只调用 `seneca.add` 方法。 540 | 541 | 要初始化插件,你需要定义一个特殊的匹配模式 `init: `,对于每一个插件,将按顺序调用此操作模式,`init` 函数必须调用其 `callback` 函数,并且不能有错误发生,如果插件初始化失败,则 Seneca 会立即退出 Node 进程。所以的插件初始化工作都必须在任何操作执行之前完成。 542 | 543 | 为了演示初始化,让我们向 `math` 插件添加简单的自定义日志记录,当插件启动时,它打开一个日志文件,并将所有操作的日志写入文件,文件需要成功打开并且可写,如果这失败,微服务启动就应该失败。 544 | 545 | ```javascript 546 | const fs = require('fs') 547 | 548 | function math(options) { 549 | 550 | // 日志记录函数,通过 init 函数创建 551 | var log 552 | 553 | // 将所有模式放在一起会上我们查找更方便 554 | this.add('role:math,cmd:sum', sum) 555 | this.add('role:math,cmd:product', product) 556 | 557 | // 这就是那个特殊的初始化操作 558 | this.add('init:math', init) 559 | 560 | function init(msg, respond) { 561 | // 将日志记录至一个特写的文件中 562 | fs.open(options.logfile, 'a', function (err, fd) { 563 | 564 | // 如果不能读取或者写入该文件,则返回错误,这会导致 Seneca 启动失败 565 | if (err) return respond(err) 566 | 567 | log = makeLog(fd) 568 | respond() 569 | }) 570 | } 571 | 572 | function sum(msg, respond) { 573 | var out = { answer: msg.left + msg.right } 574 | log('sum '+msg.left+'+'+msg.right+'='+out.answer+'\n') 575 | respond(null, out) 576 | } 577 | 578 | function product(msg, respond) { 579 | var out = { answer: msg.left * msg.right } 580 | log('product '+msg.left+'*'+msg.right+'='+out.answer+'\n') 581 | respond(null, out) 582 | } 583 | 584 | function makeLog(fd) { 585 | return function (entry) { 586 | fs.write(fd, new Date().toISOString()+' '+entry, null, 'utf8', function (err) { 587 | if (err) return console.log(err) 588 | 589 | // 确保日志条目已刷新 590 | fs.fsync(fd, function (err) { 591 | if (err) return console.log(err) 592 | }) 593 | }) 594 | } 595 | } 596 | } 597 | 598 | require('seneca')() 599 | .use(math, {logfile:'./math.log'}) 600 | .act('role:math,cmd:sum,left:1,right:2', console.log) 601 | ``` 602 | 603 | 在上面这个插件的代码中,匹配模式被组织在插件的顶部,以便它们更容易被看到,函数在这些模式下面一点被定义,您还可以看到如何使用选项提供自定义日志文件的位置(不言而喻,这不是生产日志!)。 604 | 605 | 初始化函数 `init` 执行一些异步文件系统工作,因此必须在执行任何操作之前完成。 如果失败,整个服务将无法初始化。要查看失败时的操作,可以尝试将日志文件位置更改为无效的,例如 `/math.log`。 606 | 607 | 以上代码可以在 [math-plugin-init.js](https://github.com/pantao/getting-started-seneca/blob/master/math-plugin-init.js) 文件中找到。 608 | 609 | # 创建微服务 610 | 611 | 现在让我们把 `math` 插件变成一个真正的微服务。首先,你需要组织你的插件。 `math` 插件的业务逻辑 ---- 即它提供的功能,与它以何种方式与外部世界通信是分开的,你可能会暴露一个Web服务,也有可能在消息总线上监听。 612 | 613 | 将业务逻辑(即插件定义)放在其自己的文件中是有意义的。 Node.js 模块即可完美的实现,创建一个名为 [math.js](https://github.com/pantao/getting-started-seneca/blob/master/math.js) 的文件,内容如下: 614 | 615 | ```javascript 616 | module.exports = function math(options) { 617 | 618 | this.add('role:math,cmd:sum', function sum(msg, respond) { 619 | respond(null, { answer: msg.left + msg.right }) 620 | }) 621 | 622 | this.add('role:math,cmd:product', function product(msg, respond) { 623 | respond(null, { answer: msg.left * msg.right }) 624 | }) 625 | 626 | this.wrap('role:math', function (msg, respond) { 627 | msg.left = Number(msg.left).valueOf() 628 | msg.right = Number(msg.right).valueOf() 629 | this.prior(msg, respond) 630 | }) 631 | } 632 | ``` 633 | 634 | 然后,我们可以在需要引用它的文件中像下面这样添加到我们的微服务系统中: 635 | 636 | ```javascript 637 | // 下面这两种方式都是等价的(还记得我们前面讲过的 `seneca.use` 方法的两个参数吗?) 638 | require('seneca')() 639 | .use(require('./math.js')) 640 | .act('role:math,cmd:sum,left:1,right:2', console.log) 641 | 642 | require('seneca')() 643 | .use('math') // 在当前目录下找到 `./math.js` 644 | .act('role:math,cmd:sum,left:1,right:2', console.log) 645 | ``` 646 | 647 | `seneca.wrap` 方法可以匹配一组模式,同使用相同的动作扩展函数覆盖至所有被匹配的模式,这与为每一个组模式手动调用 `seneca.add` 去扩展可以得到一样的效果,它需要两个参数: 648 | 649 | 1. `pin` :模式匹配模式 650 | 2. `action` :扩展的 `action` 函数 651 | 652 | `pin` 是一个可以匹配到多个模式的模式,它可以匹配到多个模式,比如 `role:math` 这个 `pin` 可以匹配到 `role:math, cmd:sum` 与 `role:math, cmd:product`。 653 | 654 | 在上面的示例中,我们在最后面的 `wrap` 函数中,确保了,任何传递给 `role:math` 的消息体中 `left` 与 `right` 值都是数字,即使我们传递了字符串,也可以被自动的转换为数字。 655 | 656 | 有时,查看 Seneca 实例中有哪些操作是被重写了是很有用的,你可以在启动应用时,加上 `--seneca.print.tree` 参数即可,我们先创建一个 [math-tree.js](https://github.com/pantao/getting-started-seneca/blob/master/math-tree.js) 文件,填入以下内容: 657 | 658 | ```javascript 659 | require('seneca')() 660 | .use('math') 661 | ``` 662 | 663 | 然后再执行它: 664 | 665 | ```bash 666 | ❯ node math-tree.js --seneca.print.tree 667 | {"kind":"notice","notice":"hello seneca abs0eg4hu04h/1483589278500/65316/3.2.2/-","level":"info","when":1483589278522} 668 | (node:65316) DeprecationWarning: 'root' is deprecated, use 'global' 669 | Seneca action patterns for instance: abs0eg4hu04h/1483589278500/65316/3.2.2/- 670 | ├─┬ cmd:sum 671 | │ └─┬ role:math 672 | │ └── # math, (15fqzd54pnsp), 673 | │ # math, (qqrze3ub5vhl), sum 674 | └─┬ cmd:product 675 | └─┬ role:math 676 | └── # math, (qnh86mgin4r6), 677 | # math, (4nrxi5f6sp69), product 678 | ``` 679 | 680 | 从上面你可以看到很多的键/值对,并且以树状结构展示了重写,所有的 `Action` 函数展示的格式都是 `#plugin, (action-id), function-name`。 681 | 682 | 但是,到现在为止,所有的操作都还存在于同一个进程中,接下来,让我们先创建一个名为 [math-service.js](https://github.com/pantao/getting-started-seneca/blob/master/math-service.js) 的文件,填入以下内容: 683 | 684 | ```javascript 685 | require('seneca')() 686 | .use('math') 687 | .listen() 688 | ``` 689 | 690 | 然后启动该脚本,即可启动我们的微服务,它会启动一个进程,并通过 `10101` 端口监听HTTP请求,它不是一个 Web 服务器,在此时, `HTTP` 仅仅作为消息的传输机制。 691 | 692 | 你现在可以访问 即可看到结果,或者使用 `curl` 命令: 693 | 694 | ```bash 695 | curl -d '{"role":"math","cmd":"sum","left":1,"right":2}' http://localhost:10101/act 696 | ``` 697 | 698 | 两种方式都可以看到结果: 699 | 700 | ```javascript 701 | {"answer":3} 702 | ``` 703 | 704 | 接下来,你需要一个微服务客户端 [math-client.js](https://github.com/pantao/getting-started-seneca/blob/master/math-client.js): 705 | 706 | ```javascript 707 | require('seneca')() 708 | .client() 709 | .act('role:math,cmd:sum,left:1,right:2',console.log) 710 | ``` 711 | 712 | 打开一个新的终端,执行该脚本: 713 | 714 | ```bash 715 | null { answer: 3 } { id: '7uuptvpf8iff/9wfb26kbqx55', 716 | accept: '043di4pxswq7/1483589685164/65429/3.2.2/-', 717 | track: undefined, 718 | time: 719 | { client_sent: '0', 720 | listen_recv: '0', 721 | listen_sent: '0', 722 | client_recv: 1483589898390 } } 723 | ``` 724 | 725 | 在 `Seneca` 中,我们通过 `seneca.listen` 方法创建微服务,然后通过 `seneca.client` 去与微服务进行通信。在上面的示例中,我们使用的都是 Seneca 的默认配置,比如 `HTTP` 协议监听 `10101` 端口,但 `seneca.listen` 与 `seneca.client` 方法都可以接受下面这些参数,以达到定抽的功能: 726 | 727 | - `port` :可选的数字,表示端口号; 728 | - `host` :可先的字符串,表示主机名或者IP地址; 729 | - `spec` :可选的对象,完整的定制对象 730 | 731 | > **注意**:在 Windows 系统中,如果未指定 `host`, 默认会连接 `0.0.0.0`,这是没有任何用处的,你可以设置 `host` 为 `localhost`。 732 | 733 | 只要 `client` 与 `listen` 的端口号与主机一致,它们就可以进行通信: 734 | 735 | - seneca.client(8080) → seneca.listen(8080) 736 | - seneca.client(8080, '192.168.0.2') → seneca.listen(8080, '192.168.0.2') 737 | - seneca.client({ port: 8080, host: '192.168.0.2' }) → seneca.listen({ port: 8080, host: '192.168.0.2' }) 738 | 739 | Seneca 为你提供的 **无依赖传输** 特性,让你在进行业务逻辑开发时,不需要知道消息如何传输或哪些服务会得到它们,而是在服务设置代码或配置中指定,比如 `math.js` 插件中的代码永远不需要改变,我们就可以任意的改变传输方式。 740 | 741 | 虽然 `HTTP` 协议很方便,但是并不是所有时间都合适,另一个常用的协议是 `TCP`,我们可以很容易的使用 `TCP` 协议来进行数据的传输,尝试下面这两个文件: 742 | 743 | [math-service-tcp.js](https://github.com/pantao/getting-started-seneca/blob/master/math-service-tcp.js) : 744 | 745 | ```javascript 746 | require('seneca')() 747 | .use('math') 748 | .listen({type: 'tcp'}) 749 | ``` 750 | 751 | [math-client-tcp.js](https://github.com/pantao/getting-started-seneca/blob/master/math-client-tcp.js) 752 | 753 | ```javascript 754 | require('seneca')() 755 | .client({type: 'tcp'}) 756 | .act('role:math,cmd:sum,left:1,right:2',console.log) 757 | ``` 758 | 759 | 默认情况下, `client/listen` 并未指定哪些消息将发送至哪里,只是本地定义了模式的话,会发送至本地的模式中,否则会全部发送至服务器中,我们可以通过一些配置来定义哪些消息将发送到哪些服务中,你可以使用一个 `pin` 参数来做这件事情。 760 | 761 | 让我们来创建一个应用,它将通过 TCP 发送所有 `role:math` 消息至服务,而把其它的所有消息都在发送至本地: 762 | 763 | [math-pin-service.js](https://github.com/pantao/getting-started-seneca/blob/master/math-pin-service.js): 764 | 765 | ```javascript 766 | require('seneca')() 767 | 768 | .use('math') 769 | 770 | // 监听 role:math 消息 771 | // 重要:必须匹配客户端 772 | .listen({ type: 'tcp', pin: 'role:math' }) 773 | ``` 774 | 775 | [math-pin-client.js](https://github.com/pantao/getting-started-seneca/blob/master/math-pin-client.js): 776 | 777 | ```javascript 778 | require('seneca')() 779 | 780 | // 本地模式 781 | .add('say:hello', function (msg, respond){ respond(null, {text: "Hi!"}) }) 782 | 783 | // 发送 role:math 模式至服务 784 | // 注意:必须匹配服务端 785 | .client({ type: 'tcp', pin: 'role:math' }) 786 | 787 | // 远程操作 788 | .act('role:math,cmd:sum,left:1,right:2',console.log) 789 | 790 | // 本地操作 791 | .act('say:hello',console.log) 792 | ``` 793 | 794 | 你可以通过各种过滤器来自定义日志的打印,以跟踪消息的流动,使用 `--seneca...` 参数,支持以下配置: 795 | 796 | - `date-time`: log 条目何时被创建; 797 | - `seneca-id`: Seneca process ID; 798 | - `level`:`DEBUG`、`INFO`、`WARN`、`ERROR` 以及 `FATAL` 中任何一个; 799 | - `type`:条目编码,比如 `act`、`plugin` 等; 800 | - `plugin`:插件名称,不是插件内的操作将表示为 `root$`; 801 | - `case`: 条目的事件:`IN`、`ADD`、`OUT` 等 802 | - `action-id/transaction-id`:跟踪标识符,_在网络中永远保持一致_; 803 | - `pin`:`action` 匹配模式; 804 | - `message`:入/出参消息体 805 | 806 | 如果你运行上面的进程,使用了 `--seneca.log.all`,则会打印出所有日志,如果你只想看 `math` 插件打印的日志,可以像下面这样启动服务: 807 | 808 | ```bash 809 | node math-pin-service.js --seneca.log=plugin:math 810 | ``` 811 | 812 | # Web 服务集成 813 | 814 | Seneca不是一个Web框架。 但是,您仍然需要将其连接到您的Web服务API,你永远要记住的是,不要将你的内部行为模式暴露在外面,这不是一个好的安全的实践,相反的,你应该定义一组API模式,比如用属性 `role:api`,然后你可以将它们连接到你的内部微服务。 815 | 816 | 下面是我们定义 [api.js](https://github.com/pantao/getting-started-seneca/blob/master/api.js) 插件。 817 | 818 | ```javascript 819 | module.exports = function api(options) { 820 | 821 | var validOps = { sum:'sum', product:'product' } 822 | 823 | this.add('role:api,path:calculate', function (msg, respond) { 824 | var operation = msg.args.params.operation 825 | var left = msg.args.query.left 826 | var right = msg.args.query.right 827 | this.act('role:math', { 828 | cmd: validOps[operation], 829 | left: left, 830 | right: right, 831 | }, respond) 832 | }) 833 | 834 | this.add('init:api', function (msg, respond) { 835 | this.act('role:web',{routes:{ 836 | prefix: '/api', 837 | pin: 'role:api,path:*', 838 | map: { 839 | calculate: { GET:true, suffix:'/{operation}' } 840 | } 841 | }}, respond) 842 | }) 843 | 844 | } 845 | ``` 846 | 847 | 然后,我们使用 `hapi` 作为Web框架,建了 [hapi-app.js](https://github.com/pantao/getting-started-seneca/blob/master/hapi-app.js) 应用: 848 | 849 | ```javascript 850 | const Hapi = require('hapi'); 851 | const Seneca = require('seneca'); 852 | const SenecaWeb = require('seneca-web'); 853 | 854 | const config = { 855 | adapter: require('seneca-web-adapter-hapi'), 856 | context: (() => { 857 | const server = new Hapi.Server(); 858 | server.connection({ 859 | port: 3000 860 | }); 861 | 862 | server.route({ 863 | path: '/routes', 864 | method: 'get', 865 | handler: (request, reply) => { 866 | const routes = server.table()[0].table.map(route => { 867 | return { 868 | path: route.path, 869 | method: route.method.toUpperCase(), 870 | description: route.settings.description, 871 | tags: route.settings.tags, 872 | vhost: route.settings.vhost, 873 | cors: route.settings.cors, 874 | jsonp: route.settings.jsonp, 875 | } 876 | }) 877 | reply(routes) 878 | } 879 | }); 880 | 881 | return server; 882 | })() 883 | }; 884 | 885 | const seneca = Seneca() 886 | .use(SenecaWeb, config) 887 | .use('math') 888 | .use('api') 889 | .ready(() => { 890 | const server = seneca.export('web/context')(); 891 | server.start(() => { 892 | server.log('server started on: ' + server.info.uri); 893 | }); 894 | }); 895 | ``` 896 | 897 | 启动 `hapi-app.js` 之后,访问 ,你便可以看到下面这样的信息: 898 | 899 | ```javascript 900 | [ 901 | { 902 | "path": "/routes", 903 | "method": "GET", 904 | "cors": false 905 | }, 906 | { 907 | "path": "/api/calculate/{operation}", 908 | "method": "GET", 909 | "cors": false 910 | } 911 | ] 912 | ``` 913 | 914 | 这表示,我们已经成功的将模式匹配更新至 `hapi` 应用的路由中。访问 ,将得到结果: 915 | 916 | ```javascript 917 | {"answer":3} 918 | ``` 919 | 920 | 在上面的示例中,我们直接将 `math` 插件也加载到了 `seneca` 实例中,其实我们可以更加合理的进行这种操作,如 [hapi-app-client.js](https://github.com/pantao/getting-started-seneca/blob/master/hapi-app-client.js) 文件所示: 921 | 922 | ```javascript 923 | ... 924 | const seneca = Seneca() 925 | .use(SenecaWeb, config) 926 | .use('api') 927 | .client({type: 'tcp', pin: 'role:math'}) 928 | .ready(() => { 929 | const server = seneca.export('web/context')(); 930 | server.start(() => { 931 | server.log('server started on: ' + server.info.uri); 932 | }); 933 | }); 934 | ``` 935 | 936 | 我们不注册 `math` 插件,而是使用 `client` 方法,将 `role:math` 发送给 `math-pin-service.js` 的服务,并且使用的是 `tcp` 连接,没错,你的微服务就是这样成型了。 937 | 938 | **注意:永远不要使用外部输入创建操作的消息体,永远显示地在内部创建,这可以有效避免注入攻击。** 939 | 940 | 在上面的的初始化函数中,调用了一个 `role:web` 的模式操作,并且定义了一个 `routes` 属性,这将定义一个URL地址与操作模式的匹配规则,它有下面这些参数: 941 | 942 | - `prefix`:URL 前缀 943 | - `pin`: 需要映射的模式集 944 | - `map`:要用作 URL Endpoint 的 `pin` 通配符属性列表 945 | 946 | 你的URL地址将开始于 `/api/`。 947 | 948 | `rol:api, path:*` 这个 `pin` 表示,映射任何有 `role="api"` 键值对,同时 `path` 属性被定义了的模式,在本例中,只有 `role:api,path:calculate` 符合该模式。 949 | 950 | `map` 属性是一个对象,它有一个 `calculate` 属性,对应的URL地址开始于:`/api/calculate`。 951 | 952 | 按着, `calculate` 的值是一个对象,它表示了 `HTTP` 的 `GET` 方法是被允许的,并且URL应该有参数化的后缀(后缀就类于 `hapi` 的 `route` 规则中一样)。 953 | 954 | 所以,你的完整地址是 `/api/calculate/{operation}`。 955 | 956 | 然后,其它的消息属性都将从 URL query 对象或者 JSON body 中获得,在本示例中,因为使用的是 GET 方法,所以没有 body。 957 | 958 | `SenecaWeb` 将会通过 `msg.args` 来描述一次请求,它包括: 959 | 960 | - `body`:HTTP 请求的 `payload` 部分; 961 | - `query`:请求的 `querystring`; 962 | - `params`:请求的路径参数。 963 | 964 | 现在,启动前面我们创建的微服务: 965 | 966 | ```bash 967 | node math-pin-service.js --seneca.log=plugin:math 968 | ``` 969 | 970 | 然后再启动我们的应用: 971 | 972 | ```bash 973 | node hapi-app.js --seneca.log=plugin:web,plugin:api 974 | ``` 975 | 976 | 访问下面的地址: 977 | 978 | - 得到 `{"answer":6}` 979 | - 得到 `{"answer":5}` 980 | 981 | # 数据持久化 982 | 983 | 一个真实的系统,肯定需要持久化数据,在Seneca中,你可以执行任何您喜欢的操作,使用任何类型的数据库层,但是,为什么不使用模式匹配和微服务的力量,使你的开发更轻松? 984 | 985 | 模式匹配还意味着你可以推迟有关微服务数据的争论,比如服务是否应该"拥有"数据,服务是否应该访问共享数据库等,模式匹配意味着你可以在随后的任何时间重新配置你的系统。 986 | 987 | [seneca-entity](https://github.com/senecajs/seneca-entity) 提供了一个简单的数据抽象层(ORM),基于以下操作: 988 | 989 | - `load`:根据实体标识加载一个实体; 990 | - `save`:创建或更新(如果你提供了一个标识的话)一个实体; 991 | - `list`:列出匹配查询条件的所有实体; 992 | - `remove`:删除一个标识指定的实体。 993 | 994 | 它们的匹配模式分别是: 995 | 996 | - `load`: `role:entity,cmd:load,name:` 997 | - `save`: `role:entity,cmd:save,name:` 998 | - `list`: `role:entity,cmd:list,name:` 999 | - `remove`: `role:entity,cmd:remove,name:` 1000 | 1001 | 任何实现了这些模式的插件都可以被用于提供数据库(比如 [MySQL](https://www.npmjs.com/package/seneca-mysql-store))访问。 1002 | 1003 | 当数据的持久化与其它的一切都基于相同的机制提供时,微服务的开发将变得更容易,而这种机制,便是模式匹配消息。 1004 | 1005 | 由于直接使用数据持久性模式可能变得乏味,所以 `seneca` 实体还提供了一个更熟悉的 `ActiveRecord` 风格的接口,要创建记录对象,请调用 `seneca.make` 方法。 记录对象有方法 `load$`、`save$`、`list$` 以及 `remove$`(所有方法都带有 `$` 后缀,以防止与数据字段冲突),数据字段只是对象属性。 1006 | 1007 | 通过 `npm` 安装 `seneca-entity`, 然后在你的应用中使用 `seneca.use()` 方法加载至你的 `seneca` 实例。 1008 | 1009 | 现在让我们先创建一个简单的数据实体,它保存 `book` 的详情。 1010 | 1011 | 文件 [book.js](https://github.com/pantao/getting-started-seneca/blob/master/book.js) 1012 | 1013 | ```javascript 1014 | const seneca = require('seneca')(); 1015 | seneca.use('basic').use('entity'); 1016 | 1017 | const book = seneca.make('book'); 1018 | book.title = 'Action in Seneca'; 1019 | book.price = 9.99; 1020 | 1021 | // 发送 role:entity,cmd:save,name:book 消息 1022 | book.save$( console.log ); 1023 | ``` 1024 | 1025 | 在上面的示例中,我们还使用了 [seneca-basic](https://github.com/senecajs/seneca-basic),它是 `seneca-entity` 依赖的插件。 1026 | 1027 | 执行上面的代码之后,我们可以看到下面这样的日志: 1028 | 1029 | ```bash 1030 | ❯ node book.js 1031 | null $-/-/book;id=byo81d;{title:Action in Seneca,price:9.99} 1032 | ``` 1033 | 1034 | > Seneca 内置了 [mem-store](https://www.npmjs.com/package/seneca-mem-store),这使得我们在本示例中,不需要使用任何其它数据库的支持也能进行完整的数据库持久操作(虽然,它并不是真正的持久化了)。 1035 | 1036 | 由于数据的持久化永远都是使用的同样的消息模式集,所以,你可以非常简单的交互数据库,比如,你可能在开发的过程中使用的是 [MongoDB](https://www.npmjs.com/package/seneca-mongo-store),而后,开发完成之后,在生产环境中使用 [Postgres](https://www.npmjs.com/package/seneca-postgres-store)。 1037 | 1038 | 下面让我他创建一个简单的线上书店,我们可以通过它,快速的添加新书、获取书的详细信息以及购买一本书: 1039 | 1040 | [book-store.js](https://github.com/pantao/getting-started-seneca/blob/master/book-store.js) 1041 | 1042 | ```javascript 1043 | module.exports = function(options) { 1044 | 1045 | // 从数据库中,查询一本ID为 `msg.id` 的书,我们使用了 `load$` 方法 1046 | this.add('role:store, get:book', function(msg, respond) { 1047 | this.make('book').load$(msg.id, respond); 1048 | }); 1049 | 1050 | // 向数据库中添加一本书,书的数据为 `msg.data`,我们使用了 `data$` 方法 1051 | this.add('role:store, add:book', function(msg, respond) { 1052 | this.make('book').data$(msg.data).save$(respond); 1053 | }); 1054 | 1055 | // 创建一条新的支付订单(在真实的系统中,经常是由商品详情布中的 *购买* 按钮触 1056 | // 发的事件),先是查询出ID为 `msg.id` 的书本,若查询出错,则直接返回错误, 1057 | // 否则,将书本的信息复制给 `purchase` 实体,并保存该订单,然后,我们发送了 1058 | // 一条 `role:store,info:purchase` 消息(但是,我们并不接收任何响应), 1059 | // 这条消息只是通知整个系统,我们现在有一条新的订单产生了,但是我并不关心谁会 1060 | // 需要它。 1061 | this.add('role:store, cmd:purchase', function(msg, respond) { 1062 | this.make('book').load$(msg.id, function(err, book) { 1063 | if (err) return respond(err); 1064 | 1065 | this 1066 | .make('purchase') 1067 | .data$({ 1068 | when: Date.now(), 1069 | bookId: book.id, 1070 | title: book.title, 1071 | price: book.price, 1072 | }) 1073 | .save$(function(err, purchase) { 1074 | if (err) return respond(err); 1075 | 1076 | this.act('role:store,info:purchase', { 1077 | purchase: purchase 1078 | }); 1079 | respond(null, purchase); 1080 | }); 1081 | }); 1082 | }); 1083 | 1084 | // 最后,我们实现了 `role:store, info:purchase` 模式,就只是简单的将信息 1085 | // 打印出来, `seneca.log` 对象提供了 `debug`、`info`、`warn`、`error`、 1086 | // `fatal` 方法用于打印相应级别的日志。 1087 | this.add('role:store, info:purchase', function(msg, respond) { 1088 | this.log.info('purchase', msg.purchase); 1089 | respond(); 1090 | }); 1091 | }; 1092 | ``` 1093 | 1094 | 接下来,我们可以创建一个简单的单元测试,以验证我们前面创建的程序: 1095 | 1096 | [boot-store-test.js](https://github.com/pantao/getting-started-seneca/blob/master/book-store-test.js) 1097 | 1098 | ```javascript 1099 | // 使用 Node 内置的 `assert` 模块 1100 | const assert = require('assert') 1101 | 1102 | const seneca = require('seneca')() 1103 | .use('basic') 1104 | .use('entity') 1105 | .use('book-store') 1106 | .error(assert.fail) 1107 | 1108 | // 添加一本书 1109 | addBook() 1110 | 1111 | function addBook() { 1112 | seneca.act( 1113 | 'role:store,add:book,data:{title:Action in Seneca,price:9.99}', 1114 | function(err, savedBook) { 1115 | 1116 | this.act( 1117 | 'role:store,get:book', { 1118 | id: savedBook.id 1119 | }, 1120 | function(err, loadedBook) { 1121 | 1122 | assert.equal(loadedBook.title, savedBook.title) 1123 | 1124 | purchase(loadedBook); 1125 | } 1126 | ) 1127 | } 1128 | ) 1129 | } 1130 | 1131 | function purchase(book) { 1132 | seneca.act( 1133 | 'role:store,cmd:purchase', { 1134 | id: book.id 1135 | }, 1136 | function(err, purchase) { 1137 | assert.equal(purchase.bookId, book.id) 1138 | } 1139 | ) 1140 | } 1141 | ``` 1142 | 1143 | 执行该测试: 1144 | 1145 | ```bash 1146 | ❯ node book-store-test.js 1147 | ["purchase",{"entity$":"-/-/purchase","when":1483607360925,"bookId":"a2mlev","title":"Action in Seneca","price":9.99,"id":"i28xoc"}] 1148 | ``` 1149 | 1150 | 在一个生产应用中,我们对于上面的订单数据,可能会有单独的服务进行监控,而不是像上面这样,只是打印一条日志出来,那么,我们现在来创建一个新的服务,用于收集订单数据: 1151 | 1152 | [book-store-stats.js](https://github.com/pantao/getting-started-seneca/blob/master/book-store-stats.js) 1153 | 1154 | ```javascript 1155 | const stats = {}; 1156 | 1157 | require('seneca')() 1158 | .add('role:store,info:purchase', function(msg, respond) { 1159 | const id = msg.purchase.bookId; 1160 | stats[id] = stats[id] || 0; 1161 | stats[id]++; 1162 | console.log(stats); 1163 | respond(); 1164 | }) 1165 | .listen({ 1166 | port: 9003, 1167 | host: 'localhost', 1168 | pin: 'role:store,info:purchase' 1169 | }); 1170 | ``` 1171 | 1172 | 然后,更新 `book-store-test.js` 文件: 1173 | 1174 | ```javascript 1175 | const seneca = require('seneca')() 1176 | .use('basic') 1177 | .use('entity') 1178 | .use('book-store') 1179 | .client({port:9003,host: 'localhost', pin:'role:store,info:purchase'}) 1180 | .error(assert.fail); 1181 | ``` 1182 | 1183 | 此时,当有新的订单产生时,就会通知到订单监控服务了。 1184 | 1185 | ## 将所有服务集成到一起 1186 | 1187 | 通过上面的所有步骤,我们现在已经有四个服务了: 1188 | 1189 | - [book-store-stats.js](https://github.com/pantao/getting-started-seneca/blob/master/book-store-stats.js) : 用于收集书店的订单信息; 1190 | - [book-store-service.js](https://github.com/pantao/getting-started-seneca/blob/master/book-store-service.js) :提供书店相关的功能; 1191 | - [math-pin-service.js](https://github.com/pantao/getting-started-seneca/blob/master/math-pin-service.js):提供一些数学相关的服务; 1192 | - [app-all.js](https://github.com/pantao/getting-started-seneca/blob/master/app-all.js):Web 服务 1193 | 1194 | `book-store-stats` 与 `math-pin-service` 我们已经有了,所以,直接启动即可: 1195 | 1196 | ```bash 1197 | node math-pin-service.js --seneca.log.all 1198 | node book-store-stats.js --seneca.log.all 1199 | ``` 1200 | 1201 | 现在,我们需要一个 `book-store-service` : 1202 | 1203 | ```javascript 1204 | require('seneca')() 1205 | .use('basic') 1206 | .use('entity') 1207 | .use('book-store') 1208 | .listen({ 1209 | port: 9002, 1210 | host: 'localhost', 1211 | pin: 'role:store' 1212 | }) 1213 | .client({ 1214 | port: 9003, 1215 | host: 'localhost', 1216 | pin: 'role:store,info:purchase' 1217 | }); 1218 | ``` 1219 | 1220 | 该服务接收任何 `role:store` 消息,但同时又将任何 `role:store,info:purchase` 消息发送至网络,**永远都要记住, client 与 listen 的 pin 配置必须完全一致**。 1221 | 1222 | 现在,我们可以启动该服务: 1223 | 1224 | ```bash 1225 | node book-store-service.js --seneca.log.all 1226 | ``` 1227 | 1228 | 然后,创建我们的 `app-all.js`,首选,复制 `api.js` 文件到 [api-all.js](https://github.com/pantao/getting-started-seneca/blob/master/api-all.js),这是我们的API。 1229 | 1230 | ```javascript 1231 | module.exports = function api(options) { 1232 | 1233 | var validOps = { 1234 | sum: 'sum', 1235 | product: 'product' 1236 | } 1237 | 1238 | this.add('role:api,path:calculate', function(msg, respond) { 1239 | var operation = msg.args.params.operation 1240 | var left = msg.args.query.left 1241 | var right = msg.args.query.right 1242 | this.act('role:math', { 1243 | cmd: validOps[operation], 1244 | left: left, 1245 | right: right, 1246 | }, respond) 1247 | }); 1248 | 1249 | this.add('role:api,path:store', function(msg, respond) { 1250 | let id = null; 1251 | if (msg.args.query.id) id = msg.args.query.id; 1252 | if (msg.args.body.id) id = msg.args.body.id; 1253 | 1254 | const operation = msg.args.params.operation; 1255 | const storeMsg = { 1256 | role: 'store', 1257 | id: id 1258 | }; 1259 | if ('get' === operation) storeMsg.get = 'book'; 1260 | if ('purchase' === operation) storeMsg.cmd = 'purchase'; 1261 | this.act(storeMsg, respond); 1262 | }); 1263 | 1264 | this.add('init:api', function(msg, respond) { 1265 | this.act('role:web', { 1266 | routes: { 1267 | prefix: '/api', 1268 | pin: 'role:api,path:*', 1269 | map: { 1270 | calculate: { 1271 | GET: true, 1272 | suffix: '/{operation}' 1273 | }, 1274 | store: { 1275 | GET: true, 1276 | POST: true, 1277 | suffix: '/{operation}' 1278 | } 1279 | } 1280 | } 1281 | }, respond) 1282 | }) 1283 | 1284 | } 1285 | ``` 1286 | 1287 | 最后, [app-all.js](https://github.com/pantao/getting-started-seneca/blob/master/app-all.js): 1288 | 1289 | ```javascript 1290 | const Hapi = require('hapi'); 1291 | const Seneca = require('seneca'); 1292 | const SenecaWeb = require('seneca-web'); 1293 | 1294 | const config = { 1295 | adapter: require('seneca-web-adapter-hapi'), 1296 | context: (() => { 1297 | const server = new Hapi.Server(); 1298 | server.connection({ 1299 | port: 3000 1300 | }); 1301 | 1302 | server.route({ 1303 | path: '/routes', 1304 | method: 'get', 1305 | handler: (request, reply) => { 1306 | const routes = server.table()[0].table.map(route => { 1307 | return { 1308 | path: route.path, 1309 | method: route.method.toUpperCase(), 1310 | description: route.settings.description, 1311 | tags: route.settings.tags, 1312 | vhost: route.settings.vhost, 1313 | cors: route.settings.cors, 1314 | jsonp: route.settings.jsonp, 1315 | } 1316 | }) 1317 | reply(routes) 1318 | } 1319 | }); 1320 | 1321 | return server; 1322 | })() 1323 | }; 1324 | 1325 | const seneca = Seneca() 1326 | .use(SenecaWeb, config) 1327 | .use('basic') 1328 | .use('entity') 1329 | .use('math') 1330 | .use('api-all') 1331 | .client({ 1332 | type: 'tcp', 1333 | pin: 'role:math' 1334 | }) 1335 | .client({ 1336 | port: 9002, 1337 | host: 'localhost', 1338 | pin: 'role:store' 1339 | }) 1340 | .ready(() => { 1341 | const server = seneca.export('web/context')(); 1342 | server.start(() => { 1343 | server.log('server started on: ' + server.info.uri); 1344 | }); 1345 | }); 1346 | 1347 | // 创建一本示例书籍 1348 | seneca.act( 1349 | 'role:store,add:book', { 1350 | data: { 1351 | title: 'Action in Seneca', 1352 | price: 9.99 1353 | } 1354 | }, 1355 | console.log 1356 | ) 1357 | ``` 1358 | 1359 | 启动该服务: 1360 | 1361 | ```bash 1362 | node app-all.js --seneca.log.all 1363 | ``` 1364 | 1365 | 从控制台我们可以看到下面这样的消息: 1366 | 1367 | ```bash 1368 | null $-/-/book;id=0r7mg7;{title:Action in Seneca,price:9.99} 1369 | ``` 1370 | 1371 | 这表示成功创建了一本ID为 `0r7mg7` 的书籍,现在,我们访问 [http://localhost:3000/api/store/get?id=0r7mg7](http://localhost:3000/api/store/get?id=0r7mg7) 即可查看该ID的书籍详情(ID是随机的,所以,你生成的ID可能并不是这样的)。 1372 | 1373 | [http://localhost:3000/routes](http://localhost:3000/routes) 可以查看所有的路由。 1374 | 1375 | 然后我们可创建一个新的购买订单: 1376 | 1377 | ```bash 1378 | curl -d '{"id":"0r7mg7"}' -H "content-type:application/json" http://localhost:3000/api/store/purchase 1379 | {"when":1483609872715,"bookId":"0r7mg7","title":"Action in Seneca","price":9.99,"id":"8suhf4"} 1380 | ``` 1381 | 1382 | 访问 [http://localhost:3000/api/calculate/sum?left=2&right=3](http://localhost:3000/api/calculate/sum?left=2&right=3) 可以得到 `{"answer":5}`。 1383 | 1384 | ## 最佳 Seneca 应用结构实践 1385 | 1386 | ### 推荐你这样做 1387 | 1388 | - 将业务逻辑与执行分开,放在单独的插件中,比如不同的Node模块、不同的项目甚至同一个项目下不同的文件都是可以的; 1389 | 1390 | - 使用执行脚本撰写您的应用程序,不要害怕为不同的上下文使用不同的脚本,它们看上去应该很短,比如像下面这样: 1391 | 1392 | ```javascript 1393 | var SOME_CONFIG = process.env.SOME_CONFIG || 'some-default-value' 1394 | 1395 | require('seneca')({ some_options: 123 }) 1396 | 1397 | // 已存在的 Seneca 插件 1398 | .use('community-plugin-0') 1399 | .use('community-plugin-1', {some_config: SOME_CONFIG}) 1400 | .use('community-plugin-2') 1401 | 1402 | // 业务逻辑插件 1403 | .use('project-plugin-module') 1404 | .use('../plugin-repository') 1405 | .use('./lib/local-plugin') 1406 | 1407 | .listen( ... ) 1408 | .client( ... ) 1409 | 1410 | .ready( function() { 1411 | // 当 Seneca 启动成功之后的自定义脚本 1412 | }) 1413 | ``` 1414 | 1415 | - 插件加载顺序很重要,这当然是一件好事,可以主上你对消息的成有绝对的控制权。 1416 | 1417 | ### 不推荐你这样做 1418 | 1419 | - 将 Seneca 应用的启动与初始化同其它框架的启动与初始化放在一起了,永远记住,保持事务的简单; 1420 | - 将 Seneca 实例当做变量到处传递。 1421 | -------------------------------------------------------------------------------- /api-all.js: -------------------------------------------------------------------------------- 1 | module.exports = function api(options) { 2 | 3 | var validOps = { 4 | sum: 'sum', 5 | product: 'product' 6 | } 7 | 8 | this.add('role:api,path:calculate', function(msg, respond) { 9 | var operation = msg.args.params.operation 10 | var left = msg.args.query.left 11 | var right = msg.args.query.right 12 | this.act('role:math', { 13 | cmd: validOps[operation], 14 | left: left, 15 | right: right, 16 | }, respond) 17 | }); 18 | 19 | this.add('role:api,path:store', function(msg, respond) { 20 | let id = null; 21 | if (msg.args.query.id) id = msg.args.query.id; 22 | if (msg.args.body.id) id = msg.args.body.id; 23 | 24 | const operation = msg.args.params.operation; 25 | const storeMsg = { 26 | role: 'store', 27 | id: id 28 | }; 29 | if ('get' === operation) storeMsg.get = 'book'; 30 | if ('purchase' === operation) storeMsg.cmd = 'purchase'; 31 | 32 | this.act(storeMsg, respond); 33 | }); 34 | 35 | this.add('init:api', function(msg, respond) { 36 | this.act('role:web', { 37 | routes: { 38 | prefix: '/api', 39 | pin: 'role:api,path:*', 40 | map: { 41 | calculate: { 42 | GET: true, 43 | suffix: '/{operation}' 44 | }, 45 | store: { 46 | GET: true, 47 | POST: true, 48 | suffix: '/{operation}' 49 | } 50 | } 51 | } 52 | }, respond) 53 | }) 54 | 55 | } 56 | -------------------------------------------------------------------------------- /api.js: -------------------------------------------------------------------------------- 1 | module.exports = function api(options) { 2 | 3 | var validOps = { sum:'sum', product:'product' } 4 | 5 | this.add('role:api,path:calculate', function (msg, respond) { 6 | var operation = msg.args.params.operation 7 | var left = msg.args.query.left 8 | var right = msg.args.query.right 9 | this.act('role:math', { 10 | cmd: validOps[operation], 11 | left: left, 12 | right: right, 13 | }, respond) 14 | }) 15 | 16 | this.add('init:api', function (msg, respond) { 17 | this.act('role:web',{routes:{ 18 | prefix: '/api', 19 | pin: 'role:api,path:*', 20 | map: { 21 | calculate: { GET:true, suffix:'/{operation}' } 22 | } 23 | }}, respond) 24 | }) 25 | 26 | } 27 | -------------------------------------------------------------------------------- /app-all.js: -------------------------------------------------------------------------------- 1 | const Hapi = require('hapi'); 2 | const Seneca = require('seneca'); 3 | const SenecaWeb = require('seneca-web'); 4 | 5 | const config = { 6 | adapter: require('seneca-web-adapter-hapi'), 7 | context: (() => { 8 | const server = new Hapi.Server(); 9 | server.connection({ 10 | port: 3000 11 | }); 12 | 13 | server.route({ 14 | path: '/routes', 15 | method: 'get', 16 | handler: (request, reply) => { 17 | const routes = server.table()[0].table.map(route => { 18 | return { 19 | path: route.path, 20 | method: route.method.toUpperCase(), 21 | description: route.settings.description, 22 | tags: route.settings.tags, 23 | vhost: route.settings.vhost, 24 | cors: route.settings.cors, 25 | jsonp: route.settings.jsonp, 26 | } 27 | }) 28 | reply(routes) 29 | } 30 | }); 31 | 32 | return server; 33 | })() 34 | }; 35 | 36 | const seneca = Seneca() 37 | .use(SenecaWeb, config) 38 | .use('basic') 39 | .use('entity') 40 | .use('math') 41 | .use('api-all') 42 | .client({ 43 | type: 'tcp', 44 | pin: 'role:math' 45 | }) 46 | .client({ 47 | port: 9002, 48 | pin: 'role:store' 49 | }) 50 | .ready(() => { 51 | const server = seneca.export('web/context')(); 52 | server.start(() => { 53 | server.log('server started on: ' + server.info.uri); 54 | }); 55 | }); 56 | 57 | // 创建一本示例书籍 58 | seneca.act( 59 | 'role:store,add:book', { 60 | data: { 61 | title: 'Action in Seneca', 62 | price: 9.99 63 | } 64 | }, 65 | console.log 66 | ) 67 | -------------------------------------------------------------------------------- /book-store-service.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | .use('basic') 3 | .use('entity') 4 | .use('book-store') 5 | .listen({ 6 | port: 9002, 7 | pin: 'role:store' 8 | }) 9 | .client({ 10 | port: 9003, 11 | pin: 'role:store,info:purchase' 12 | }); 13 | -------------------------------------------------------------------------------- /book-store-stats.js: -------------------------------------------------------------------------------- 1 | const stats = {}; 2 | 3 | require('seneca')() 4 | .add('role:store,info:purchase', function(msg, respond) { 5 | const id = msg.purchase.bookId; 6 | stats[id] = stats[id] || 0; 7 | stats[id]++; 8 | console.log(stats); 9 | respond(); 10 | }) 11 | .listen({ 12 | port: 9003, 13 | pin: 'role:store,info:purchase' 14 | }); 15 | -------------------------------------------------------------------------------- /book-store-test.js: -------------------------------------------------------------------------------- 1 | // 使用 Node 内置的 `assert` 模块 2 | const assert = require('assert') 3 | 4 | const seneca = require('seneca')() 5 | .use('basic') 6 | .use('entity') 7 | .use('book-store') 8 | .client({ 9 | port: 9003, 10 | pin: 'role:store,info:purchase' 11 | }) 12 | .error(assert.fail); 13 | 14 | // 添加一本书 15 | addBook() 16 | 17 | function addBook() { 18 | seneca.act( 19 | 'role:store,add:book,data:{title:Action in Seneca,price:9.99}', 20 | function(err, savedBook) { 21 | 22 | this.act( 23 | 'role:store,get:book', { 24 | id: savedBook.id 25 | }, 26 | function(err, loadedBook) { 27 | 28 | assert.equal(loadedBook.title, savedBook.title) 29 | 30 | purchase(loadedBook); 31 | } 32 | ) 33 | } 34 | ) 35 | } 36 | 37 | function purchase(book) { 38 | seneca.act( 39 | 'role:store,cmd:purchase', { 40 | id: book.id 41 | }, 42 | function(err, purchase) { 43 | assert.equal(purchase.bookId, book.id) 44 | } 45 | ) 46 | } 47 | -------------------------------------------------------------------------------- /book-store.js: -------------------------------------------------------------------------------- 1 | module.exports = function(options) { 2 | 3 | // 从数据库中,查询一本ID为 `msg.id` 的书,我们使用了 `load$` 方法 4 | this.add('role:store, get:book', function(msg, respond) { 5 | this.make('book').load$(msg.id, respond); 6 | }); 7 | 8 | // 向数据库中添加一本书,书的数据为 `msg.data`,我们使用了 `data$` 方法 9 | this.add('role:store, add:book', function(msg, respond) { 10 | this.make('book').data$(msg.data).save$(respond); 11 | }); 12 | 13 | // 创建一条新的支付订单(在真实的系统中,经常是由商品详情布中的 *购买* 按钮触 14 | // 发的事件),先是查询出ID为 `msg.id` 的书本,若查询出错,则直接返回错误, 15 | // 否则,将书本的信息复制给 `purchase` 实体,并保存该订单,然后,我们发送了 16 | // 一条 `role:store,info:purchase` 消息(但是,我们并不接收任何响应), 17 | // 这条消息只是通知整个系统,我们现在有一条新的订单产生了,但是我并不关心谁会 18 | // 需要它。 19 | this.add('role:store, cmd:purchase', function(msg, respond) { 20 | this.make('book').load$(msg.id, function(err, book) { 21 | if (err) return respond(err); 22 | 23 | this 24 | .make('purchase') 25 | .data$({ 26 | when: Date.now(), 27 | bookId: book.id, 28 | title: book.title, 29 | price: book.price, 30 | }) 31 | .save$(function(err, purchase) { 32 | if (err) return respond(err); 33 | 34 | this.act('role:store,info:purchase', { 35 | purchase: purchase 36 | }); 37 | respond(null, purchase); 38 | }); 39 | }); 40 | }); 41 | 42 | // 最后,我们实现了 `role:store, info:purchase` 模式,就只是简单的将信息 43 | // 打印出来, `seneca.log` 对象提供了 `debug`、`info`、`warn`、`error`、 44 | // `fatal` 方法用于打印相应级别的日志。 45 | this.add('role:store,info:purchase', function(msg, respond) { 46 | this.log.info('purchase', msg.purchase); 47 | respond(); 48 | }); 49 | }; 50 | -------------------------------------------------------------------------------- /book.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')(); 2 | seneca.use('basic').use('entity'); 3 | 4 | const book = seneca.make('book'); 5 | book.title = 'Action in Seneca'; 6 | book.price = 9.99; 7 | 8 | // 发送 role:entity,cmd:save,name:book 消息 9 | book.save$( console.log ); 10 | -------------------------------------------------------------------------------- /hapi-app-client.js: -------------------------------------------------------------------------------- 1 | const Hapi = require('hapi'); 2 | const Seneca = require('seneca'); 3 | const SenecaWeb = require('seneca-web'); 4 | 5 | const config = { 6 | adapter: require('seneca-web-adapter-hapi'), 7 | context: (() => { 8 | const server = new Hapi.Server(); 9 | server.connection({ 10 | port: 3000 11 | }); 12 | 13 | server.route({ 14 | path: '/routes', 15 | method: 'get', 16 | handler: (request, reply) => { 17 | const routes = server.table()[0].table.map(route => { 18 | return { 19 | path: route.path, 20 | method: route.method.toUpperCase(), 21 | description: route.settings.description, 22 | tags: route.settings.tags, 23 | vhost: route.settings.vhost, 24 | cors: route.settings.cors, 25 | jsonp: route.settings.jsonp, 26 | } 27 | }) 28 | reply(routes) 29 | } 30 | }); 31 | 32 | return server; 33 | })() 34 | }; 35 | 36 | const seneca = Seneca() 37 | .use(SenecaWeb, config) 38 | .use('api') 39 | .client({type: 'tcp', pin: 'role:math'}) 40 | .ready(() => { 41 | const server = seneca.export('web/context')(); 42 | server.start(() => { 43 | server.log('server started on: ' + server.info.uri); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /hapi-app.js: -------------------------------------------------------------------------------- 1 | const Hapi = require('hapi'); 2 | const Seneca = require('seneca'); 3 | const SenecaWeb = require('seneca-web'); 4 | 5 | const config = { 6 | adapter: require('seneca-web-adapter-hapi'), 7 | context: (() => { 8 | const server = new Hapi.Server(); 9 | server.connection({ 10 | port: 3000 11 | }); 12 | 13 | server.route({ 14 | path: '/routes', 15 | method: 'get', 16 | handler: (request, reply) => { 17 | const routes = server.table()[0].table.map(route => { 18 | return { 19 | path: route.path, 20 | method: route.method.toUpperCase(), 21 | description: route.settings.description, 22 | tags: route.settings.tags, 23 | vhost: route.settings.vhost, 24 | cors: route.settings.cors, 25 | jsonp: route.settings.jsonp, 26 | } 27 | }) 28 | reply(routes) 29 | } 30 | }); 31 | 32 | return server; 33 | })() 34 | }; 35 | 36 | const seneca = Seneca() 37 | .use(SenecaWeb, config) 38 | .use('math') 39 | .use('api') 40 | .ready(() => { 41 | const server = seneca.export('web/context')(); 42 | server.start(() => { 43 | server.log('server started on: ' + server.info.uri); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /math-client-tcp.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | .client({type: 'tcp'}) 3 | .act('role:math,cmd:sum,left:1,right:2',console.log) 4 | -------------------------------------------------------------------------------- /math-client.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | .client() 3 | .act('role:math,cmd:sum,left:1,right:2',console.log) 4 | -------------------------------------------------------------------------------- /math-pin-client.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | 3 | // 本地模式 4 | .add('say:hello', function (msg, respond){ respond(null, {text: "Hi!"}) }) 5 | 6 | // 发送 role:math 模式至服务 7 | // 注意:必须匹配服务端 8 | .client({ type: 'tcp', pin: 'role:math' }) 9 | 10 | // 远程操作 11 | .act('role:math,cmd:sum,left:1,right:2',console.log) 12 | 13 | // 本地操作 14 | .act('say:hello',console.log) 15 | -------------------------------------------------------------------------------- /math-pin-service.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | 3 | .use('math') 4 | 5 | // 监听 role:math 消息 6 | // 重要:必须匹配客户端 7 | .listen({ type: 'tcp', pin: 'role:math' }) 8 | -------------------------------------------------------------------------------- /math-plugin-init.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | 3 | function math(options) { 4 | 5 | // 日志记录函数,通过 init 函数创建 6 | var log 7 | 8 | // 将所有模式放在一起会上我们查找更方便 9 | this.add('role:math,cmd:sum', sum) 10 | this.add('role:math,cmd:product', product) 11 | 12 | // 这就是那个特殊的初始化操作 13 | this.add('init:math', init) 14 | 15 | function init(msg, respond) { 16 | // 将日志记录至一个特写的文件中 17 | fs.open(options.logfile, 'a', function (err, fd) { 18 | 19 | // 如果不能读取或者写入该文件,则返回错误,这会导致 Seneca 启动失败 20 | if (err) return respond(err) 21 | 22 | log = makeLog(fd) 23 | respond() 24 | }) 25 | } 26 | 27 | function sum(msg, respond) { 28 | var out = { answer: msg.left + msg.right } 29 | log('sum '+msg.left+'+'+msg.right+'='+out.answer+'\n') 30 | respond(null, out) 31 | } 32 | 33 | function product(msg, respond) { 34 | var out = { answer: msg.left * msg.right } 35 | log('product '+msg.left+'*'+msg.right+'='+out.answer+'\n') 36 | respond(null, out) 37 | } 38 | 39 | function makeLog(fd) { 40 | return function (entry) { 41 | fs.write(fd, new Date().toISOString()+' '+entry, null, 'utf8', function (err) { 42 | if (err) return console.log(err) 43 | 44 | // 确保日志条目已刷新 45 | fs.fsync(fd, function (err) { 46 | if (err) return console.log(err) 47 | }) 48 | }) 49 | } 50 | } 51 | } 52 | 53 | require('seneca')() 54 | .use(math, {logfile:'./math.log'}) 55 | .act('role:math,cmd:sum,left:1,right:2', console.log) 56 | -------------------------------------------------------------------------------- /math-plugin.js: -------------------------------------------------------------------------------- 1 | function math(options) { 2 | 3 | this.add('role:math,cmd:sum', function (msg, respond) { 4 | respond(null, { answer: msg.left + msg.right }) 5 | }) 6 | 7 | this.add('role:math,cmd:product', function (msg, respond) { 8 | respond(null, { answer: msg.left * msg.right }) 9 | }) 10 | 11 | } 12 | 13 | require('seneca')() 14 | .use(math) 15 | .act('role:math,cmd:sum,left:1,right:2', console.log) 16 | -------------------------------------------------------------------------------- /math-service-tcp.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | .use('math') 3 | .listen({type: 'tcp'}) 4 | -------------------------------------------------------------------------------- /math-service.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | .use('math') 3 | .listen() 4 | -------------------------------------------------------------------------------- /math-tree.js: -------------------------------------------------------------------------------- 1 | require('seneca')() 2 | .use('math') 3 | -------------------------------------------------------------------------------- /math.js: -------------------------------------------------------------------------------- 1 | module.exports = function math(options) { 2 | 3 | this.add('role:math,cmd:sum', function sum(msg, respond) { 4 | respond(null, { answer: msg.left + msg.right }) 5 | }) 6 | 7 | this.add('role:math,cmd:product', function product(msg, respond) { 8 | respond(null, { answer: msg.left * msg.right }) 9 | }) 10 | 11 | this.wrap('role:math', function (msg, respond) { 12 | msg.left = Number(msg.left).valueOf() 13 | msg.right = Number(msg.right).valueOf() 14 | this.prior(msg, respond) 15 | }) 16 | } 17 | -------------------------------------------------------------------------------- /math.log: -------------------------------------------------------------------------------- 1 | 2017-01-05T03:47:26.513Z sum 1+2=3 2 | -------------------------------------------------------------------------------- /minimal-plugin.js: -------------------------------------------------------------------------------- 1 | function minimal_plugin( options ) { 2 | console.log(options) 3 | } 4 | 5 | require('seneca')() 6 | .use( minimal_plugin, {foo:'bar'} ) 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "helloworld", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "hapi": "^16.1.0", 14 | "seneca": "^3.2.2", 15 | "seneca-basic": "^0.5.0", 16 | "seneca-entity": "^1.3.0", 17 | "seneca-web": "^2.0.0", 18 | "seneca-web-adapter-hapi": "^1.0.2" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /pattern-priority-testing.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')() 2 | 3 | seneca.add({role: 'math', cmd: 'sum'}, function (msg, respond) { 4 | var sum = msg.left + msg.right 5 | respond(null, {answer: sum}) 6 | }) 7 | 8 | // 下面两条消息都匹配 role: math, cmd: sum 9 | 10 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5}, console.log) 11 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5, integer: true}, console.log) 12 | 13 | setTimeout(() => { 14 | seneca.add({role: 'math', cmd: 'sum', integer: true}, function (msg, respond) { 15 | var sum = Math.floor(msg.left) + Math.floor(msg.right) 16 | respond(null, { answer: sum }) 17 | }) 18 | 19 | // 下面这条消息同样匹配 role: math, cmd: sum 20 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5}, console.log) 21 | 22 | // 但是,也匹配 role:math,cmd:sum,integer:true 23 | // 但是因为更多属性被匹配到,所以,它的优先级更高 24 | seneca.act({role: 'math', cmd: 'sum', left: 1.5, right: 2.5, integer: true}, console.log) 25 | }, 100) 26 | -------------------------------------------------------------------------------- /product.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')(); 2 | 3 | seneca.add('role:math, cmd:product', (msg, reply) => { 4 | reply(null, { answer: ( msg.left * msg.right )}) 5 | }); 6 | 7 | seneca.act({ 8 | role: 'math', 9 | cmd: 'product', 10 | left: 3, 11 | right: 4 12 | }, (err, result) => { 13 | if (err) { 14 | return console.error(err); 15 | } 16 | console.log(result); 17 | }); 18 | -------------------------------------------------------------------------------- /sum-integer.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')(); 2 | 3 | seneca 4 | .add('role:math, cmd:sum', (msg, reply) => { 5 | reply(null, { 6 | answer: (msg.left + msg.right) 7 | }) 8 | }) 9 | .act({ 10 | role: 'math', 11 | cmd: 'sum', 12 | left: 1, 13 | right: 2 14 | }, console.log) 15 | .act({ 16 | role: 'math', 17 | cmd: 'sum', 18 | left: 1.5, 19 | right: 2.5 20 | }, console.log) 21 | -------------------------------------------------------------------------------- /sum-product.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')(); 2 | 3 | seneca.add('role:math, cmd:sum', (msg, reply) => { 4 | reply(null, { answer: ( msg.left + msg.right )}) 5 | }); 6 | 7 | seneca.add('role:math, cmd:product', (msg, reply) => { 8 | reply(null, { answer: ( msg.left * msg.right )}) 9 | }); 10 | 11 | seneca.act({role: 'math', cmd: 'sum', left: 1, right: 2}, console.log) 12 | .act({role: 'math', cmd: 'product', left: 3, right: 4}, console.log) 13 | -------------------------------------------------------------------------------- /sum-reuse.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')() 2 | 3 | seneca.add('role: math, cmd: sum', function (msg, respond) { 4 | var sum = msg.left + msg.right 5 | respond(null, {answer: sum}) 6 | }) 7 | 8 | seneca.add('role: math, cmd: sum, integer: true', function (msg, respond) { 9 | // 复用 role:math, cmd:sum 10 | this.act({ 11 | role: 'math', 12 | cmd: 'sum', 13 | left: Math.floor(msg.left), 14 | right: Math.floor(msg.right) 15 | }, respond) 16 | }) 17 | 18 | // 匹配 role:math,cmd:sum 19 | seneca.act('role: math, cmd: sum, left: 1.5, right: 2.5',console.log) 20 | 21 | // 匹配 role:math,cmd:sum,integer:true 22 | seneca.act('role: math, cmd: sum, left: 1.5, right: 2.5, integer: true', console.log) 23 | -------------------------------------------------------------------------------- /sum-valid.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')() 2 | 3 | seneca 4 | .add( 5 | 'role:math,cmd:sum', 6 | function(msg, respond) { 7 | var sum = msg.left + msg.right 8 | respond(null, { 9 | answer: sum 10 | }) 11 | }) 12 | 13 | // 重写 role:math,cmd:sum with ,添加额外的功能 14 | .add( 15 | 'role:math,cmd:sum', 16 | function(msg, respond) { 17 | 18 | // bail out early if there's a problem 19 | if (!Number.isFinite(msg.left) || 20 | !Number.isFinite(msg.right)) { 21 | return respond(new Error("left 与 right 值必须为数字。")) 22 | } 23 | 24 | // 调用上一个操作函数 role:math,cmd:sum 25 | this.prior({ 26 | role: 'math', 27 | cmd: 'sum', 28 | left: msg.left, 29 | right: msg.right, 30 | 31 | }, function(err, result) { 32 | if (err) return respond(err) 33 | 34 | result.info = msg.left + '+' + msg.right 35 | respond(null, result) 36 | }) 37 | }) 38 | 39 | // 增加了的 role:math,cmd:sum 40 | .act('role:math,cmd:sum,left:1.5,right:2.5', 41 | console.log // 打印 { answer: 4, info: '1.5+2.5' } 42 | ) 43 | -------------------------------------------------------------------------------- /sum.js: -------------------------------------------------------------------------------- 1 | const seneca = require('seneca')(); 2 | 3 | /** 4 | * `seneca.add` 方法,添加了一个新的动作模式(*Action Pattern*)至 `Seneca` 实例中, 5 | * 它有两个参数: 6 | * 7 | * 1. `pattern` :用于匹配 Seneca 实例中 `JSON` 消息体的模式; 8 | * 2. `action` :当模式被匹配时执行的操作 9 | */ 10 | seneca.add('role:math, cmd:sum', (msg, reply) => { 11 | reply(null, { answer: ( msg.left + msg.right )}) 12 | }); 13 | 14 | /** 15 | * `seneca.act` 方法同样有两个参数: 16 | * 17 | * 1. `msg` :作为纯对象提供的待匹配的入站消息; 18 | * 2. `respond` :用于接收并处理响应信息的回调函数。 19 | */ 20 | seneca.act({ 21 | role: 'math', 22 | cmd: 'sum', 23 | left: 1, 24 | right: 2 25 | }, (err, result) => { 26 | if (err) { 27 | return console.error(err); 28 | } 29 | console.log(result); 30 | }); 31 | --------------------------------------------------------------------------------