美文网首页
开源的云原生开发平台:Micro

开源的云原生开发平台:Micro

作者: 翟志军 | 来源:发表于2021-01-27 07:52 被阅读0次
    image.png

    介绍

    随着“微服务”在企业里的广泛采用,如何快速的创建标准微服务成为一个问题。Micro为了我们提供了思路。

    Micro由4部分组成:

    • Server:Micro本身的服务端
    • Framework:开发框架
    • Command Line:命令行
    • Environments:用于切换环境和多租户

    Micro服务器端架构

    image.png

    Micro框架架构

    image.png

    Micro使用样例

    1. 本地运行server端:
    micro server
    
    1. 切换到本地环境 (127.0.0.1:8081)
    micro env set local
    
    1. 登录服务端
    micro login
    
    1. 创建微服务
    # generate a service (follow instructions in output)
    micro new helloworld
    
    # run the service
    micro run helloworld
    
    # check the status
    micro status
    
    # list running services
    micro services
    
    # call the service
    micro helloworld --name=Alice
    
    # curl via the api
    curl -d '{"name": "Alice"}' http://localhost:8080/helloworld
    

    开发微服务

    Micro的开发框架内置了Grpc的支持。3步开发微服务:

    1. 定义PB文件
    syntax = "proto3";
    
    package helloworld;
    
    service Helloworld {
        rpc Call(Request) returns (Response) {}
    }
    
    message Request {
        string name = 1;
    }
    
    message Response {
        string msg = 1;
    }
    
    1. 服务器端
    package main
    
    import (
        "context"
      
        "github.com/micro/micro/v3/service"
        "github.com/micro/micro/v3/service/logger"
        pb "github.com/micro/services/helloworld/proto"
    )
    
    type Helloworld struct{}
    
    // Call is a single request handler called via client.Call or the generated client code
    func (h *Helloworld) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
        logger.Info("Received Helloworld.Call request")
        rsp.Msg = "Hello " + req.Name
        return nil
    }
    
    func main() {
        // Create service
        srv := service.New(
            service.Name("helloworld"),
        )
    
        // Register Handler
        srv.Handle(new(Helloworld))
    
        // Run the service
        if err := srv.Run(); err != nil {
            logger.Fatal(err)
        }
    }
    
    1. 开发客户端
    import (
        "context"
      
        "github.com/micro/micro/v3/service/client"
        pb "github.com/micro/services/helloworld/proto"
    )
    
    // create a new helloworld service client
    helloworld := pb.NewHelloworldService("helloworld", client.DefaultClient) 
    
    // call the endpoint Helloworld.Call
    rsp, err := helloworld.Call(context.Background(), &pb.Request{Name: "Alice"})
    

    相关文章

      网友评论

          本文标题:开源的云原生开发平台:Micro

          本文链接:https://www.haomeiwen.com/subject/asgwzktx.html