1. 软件包开发
  2. Sidecar

什么是Sidecar

Sidecar是一个外部微服务,注册到微服务中心后可以与其他微服务交互。

Sidecar是一个HTTP服务器,它提供了一个REST接口来与其他微服务通信,而不是实现完整的微服务注册和发现功能。

Sidecar本身是一个成熟的微服务节点,拥有所有功能(例如参数验证、重试、回退、超时等),这意味着在外部服务中,你不需要实现它们,只需要用Sidecar管理它们。

Features

  • write services any programming languages (which have http server & client support).
  • bundled to executable, no need to install Node.js environment for running.
  • configure Sidecar via environment variables or moleculer.config.js file.
  • contains all official transporter, cacher, discoverer, serializer libraries.
  • easy to add to any Docker image.
  • official Docker image, use it as a Sidecar pod container in Kubernetes cluster.

微服务注册

外部微服务需注册到微服务中心才能被识别和互相调用,包括可以在触发器中调用。

{
    name: "posts",
    version: 1,

    settings: {
        // It means, your HTTP server running on port 5000 and sidecar can reach it on `localhost`
        // The URLs in action/event handlers contains relative URL.
        baseUrl: "http://service.mesh:5000"
    },

    actions: {
        list: {
            params: {
                limit: "number",
                offset: "number"
            },
            // Shorthand handler URL what will be called by sidecar
            handler: "/actions/posts/list"
        }
    },

    events: {
        "user.created": {
            // Shorthand handler URL what will be called by sidecar
            handler: "/events/user.created"
        }
    }
}

函数(Actions)

服务公开的可调用的方法称为 actions。

    actions: {
        list: {
            params: {
                limit: "number",
                offset: "number"
            },
            // Shorthand handler URL what will be called by sidecar
            handler: "/actions/posts/list"
        }
    },

actions可以使用 broker.call 来调用。

const res = await broker.call("posts.list", { limit: 10, offset: 0 });

Events

您可以在 events 中订阅事件。

    events: {
        "user.created": {
            // Shorthand handler URL what will be called by sidecar
            handler: "/events/user.created"
        }
    }

可以使用broker.emit命令抛出事件。

// The `user` will be serialized to transportation.
broker.emit("user.created", user);

参考