简单的微服务框架(三) - 简单的服务间调用

使用gRPC进行简单的服务间调用

先列一下整体的架构

vserver/
├── client
│      └── main.go
├── server
│      └── main.go
├── proto
│      └── itemsapi.proto
│      └── itemsapi.pb.go

vserver/proto/路径定义proto文件itemsapi.proto

syntax = "proto3";

service ItemscdApi {
    rpc GetItems(ApiRequest) returns (ApiResponse) {}
}

message ApiRequest {
    string affid = 1;
}

message Result {
    string id = 1;
    string name = 2;
    string url = 3;
}

message ApiResponse {
    repeated Result results = 1;
    bool success = 2;
}

并执行命令生成proto.go文件

cd .\proto\
protoc --go_out=plugins=grpc:. itemsapi.proto

新建server端

vserver/server/main.go

package main

import (
    "context"
    "fmt"
    "log"
    "net"

    pb "vserver/proto"

    "google.golang.org/grpc"
)

const (
    port = ":50051"
)

//定义一个ItemscdApi并实现约定的接口
type ItemscdApi struct{}

func (s *ItemscdApi) GetItems(ctx context.Context, in *pb.ApiRequest) (*pb.ApiResponse, error) {

    fmt.Println("affid in rpc request:", in.Affid)
    re := &pb.ApiResponse{}
    re.Results = append(re.Results, &pb.Result{Id: "1", Name: "test name", Url: "localhost:8080"})
    re.Success = true
    return re, nil
}

func main() {
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    } else {
        fmt.Println("Now listen on tcp port:", port)
    }
    s := grpc.NewServer()
    pb.RegisterItemscdApiServer(s, &ItemscdApi{})
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

运行server.go

vserver\service> go run main.go
Now listen on tcp port: :50051

新建client端

package main

import (
    "context"
    "fmt"
    "log"
    pb "vserver/proto"

    "google.golang.org/grpc"
)

const (
    port = ":50051"
    ip   = "localhost"
)

func getItemsByRpc(client pb.ItemscdApiClient) {

    aff := &pb.ApiRequest{Affid: "3"}

    resp, err := client.GetItems(context.Background(), aff)
    if err != nil {
        log.Fatalf("Could not get Items", err)
    }

    if resp.Success {
        fmt.Println("results:", resp.Results)
    }
}

func main() {
    // Set up a connection to the gRPC server.
    conn, err := grpc.Dial(ip+port, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()
    // Creates a new UserClient
    client := pb.NewItemscdApiClient(conn)

    getItemsByRpc(client)
}

运行client.go

vserver\client> go run main.go
results: [id:"1" name:"test name" url:"localhost:8080" ]

这时候查看server端的输出

vserver\service> go run main.go
Now listen on tcp port: :50051
affid in rpc request: 3

两边都有预期的输出,说明简单的通过gRPC调用的服务已经完成

你可能感兴趣的:(简单的微服务框架(三) - 简单的服务间调用)