Go-zero微服务篇之RPC demo

image

先使用goctl生成一个proto然后修改一下通过proto生成pb那些等等

image

Server logic

image
逻辑处理
package logic

import (
    "context"
    "fmt"

    "server/internal/svc"
    "server/server"

    "github.com/tal-tech/go-zero/core/logx"
)

type LoginLogic struct {
    ctx    context.Context
    svcCtx *svc.ServiceContext
    logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
    return &LoginLogic{
        ctx:    ctx,
        svcCtx: svcCtx,
        Logger: logx.WithContext(ctx),
    }
}

func (l *LoginLogic) Login(in *server.LoginReq) (*server.LoginRep, error) {
    // todo: add your logic here and delete this line

    return &server.LoginRep{
        Msg:fmt.Sprintf("登陆成功:%s",in.Name),
    }, nil
}

etcd配置

image

客户端

注意:与服务的配置的etcd信息一一对应

image
package main

import (
    "context"
    "fmt"
    "log"
    pb "server/server"
    "github.com/tal-tech/go-zero/core/discov"
    "github.com/tal-tech/go-zero/zrpc"
)

func main() {
    client := zrpc.MustNewClient(zrpc.RpcClientConf{
        Etcd: discov.EtcdConf{
            Hosts: []string{"127.0.0.1:2379"},
            Key:   "server.rpc",
        },
    })
    hello := pb.NewServerClient(client.Conn())
    reply, err := hello.Login(context.Background(), &pb.LoginReq{Name: "go-zero"})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(reply.Msg)
}

你可能感兴趣的:(Go-zero微服务篇之RPC demo)