Node——微服务架构(二)

基本结构

  • 图列

    C:.
    │  app.js
    │
    ├─services01
    │      main.service.js
    │      math.service.js
    │
    └─services02
            main.service.js
            math.service.js
    

代码实现

  • app.js

    var express = require("express")
    
    var app = express()
    
    const {
        ServiceBroker
    } = require("moleculer");
    const broker = new ServiceBroker({
        nodeID: "node-0",
        transporter: "nats://localhost:4222",
        logLevel: "info",
        requestTimeout: 5 * 1000,
        requestRetry: 3
    });
    
    broker.start()
    
    app.get("/add", async function (req, res) {
        const result = await broker.call("math.add", {
            a: 5,
            b: 7
        });
        res.send({
            msg: result
        })
    })
    
    app.get("/sub", async function (req, res) {
        const result = await broker.call("math.sub", {
            a: 5,
            b: 7
        });
        res.send({
            msg: result
        })
    })
    
    app.listen(3000, () => {
        console.log("app is running...")
    })
    
  • main.service.js

    const {
        ServiceBroker
    } = require("moleculer");
    const broker = new ServiceBroker({
        nodeID: "node-1",
        transporter: "nats://localhost:4222",
        logLevel: "info",
        requestTimeout: 5 * 1000,
        requestRetry: 3
    });
    
    broker.loadService("./math.service");
    
    broker.start()
    
  • math.service.js

    module.exports = {
        name: "math",
        actions: {
            add(ctx) {
                return {
                    sum: Number(ctx.params.a) + Number(ctx.params.b),
                    from: "service01"
                };
            },
    
            sub(ctx) {
                return Number(ctx.params.a) - Number(ctx.params.b);
            }
        }
    }
    
  • service02 内部代码与 service01 一模一样,这里就不再重复

基本介绍

  • app.js 是启动项

    • node + express 向提供外部传统的 RestFul 风格接口

    • 客户通过对接口的访问,express 路由捕获到信息会通过关键字 call,触发对应的服务

  • service01、service02 是完全一样的服务

    • 内部都实现了 math 运算

    • 之所以这样设计是想证明是否实现了负载均衡

  • 消息服务器选择的是 NATS,默认端口 4222,NATS 是分布式微服务消息传输的桥梁

执行程序

  • node app.js

  • 浏览器输入 http://127.0.0.1:3000/add,返回结果:...service01,再试:...service02

  • 试验结果表明获取 service01service02 是具有随机性的,NATS 默认负载均衡就是 random 模式

原文地址:https://www.cnblogs.com/cnloop/p/9463543.html