跟着官方文档一步一步搭建基于gozero的微服务

1. 创建项目

mkdir microservice
cd microservice
go mod init zzh.com/microservice

2. 下载go-zero和goctl

2.1 设置代理

go env -w GOPROXY=https://goproxy.cn

2.1 启用GO111MODULE

  • 查看GO111MODULE是否启用

      go env GO111MODULE
    
  • 启用GO111MODULE

    go env -w GO111MODULE="on"
    

2.2 安装gozero

GOPROXY=https://goproxy.cn/,direct go get -u github.com/tal-tech/go-zero

3. 下载安装goctl

3.1 安装goctl

goctl默认安装在 G O P A T H 目 录 下 , 需 要 将 GOPATH目录下,需要将 GOPATHGOPATH设置到paths文件中。

  • 设置paths
vi /etc/paths
// 在文件末尾添加如下代码
$GOPATH/bin
  • 安装goctl
GOPROXY=https://goproxy.cn/,direct go install github.com/zeromicro/go-zero/tools/goctl@latest

3.2 验证goctl安装

goctl -v

4. 安装protoc,protoc-gen-go,protoc-gen-grpc-go

goctl env check -i -f

如果mac下安装出错,可以下载源码安装或使用brew安装protobuf,通过命令安装protoc-gen-go,protoc-gen-grpc-go

brew install protobuf 
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

5. 创建微服务

跟着示例创建一个user的RPC服务和一个order的API服务。

5.1 创建user RPC服务

  1. 创建目录

    cd microservice
    mkdir -p user/rpc
    
  2. 创建user.proto添加getUser方法

     cd user/rpc
     vim user.proto
    

    rpc定义代码如下(go-zero官方文档代码):

     syntax = "proto3";
     
     package user;
     
     // protoc-gen-go 版本大于1.4.0, proto文件需要加上go_package,否则无法生成
     option go_package = "./user";
     
     message IdRequest {
         string id = 1;
     }
     
     message UserResponse {
         // 用户id
         string id = 1;
         // 用户名称
         string name = 2;
         // 用户性别
         string gender = 3;
     }
     
     service User {
         rpc getUser(IdRequest) returns(UserResponse);
     }
    
  3. 调用goctl命令自动生成代码

     goctl rpc protoc user.proto --go_out=./types --go-grpc_out=./types --zrpc_out=.
    
  4. 修改获取用户逻辑
    获取用户逻辑

5.2 创建user API服务

  1. 创建API目录并且进入到api目录

    mkdir -p order/api && cd order/api
    
  2. 创建order.api文件

      type(
         OrderReq {
             Id string `path:"id"`
         }
     
         OrderReply {
             Id string `json:"id"`
             Name string `json:"name"`
         }
      )
       service order {
           @handler getOrder
           get /api/order/get/:id (OrderReq) returns (OrderReply)
       }
    
  3. 生成order API代码

     goctl api go -api order.api -dir .
    
  4. 添加user rpc配置

    vim internal/config/config.go
    

    修改config.go配置

       package config
       
       import (
           "github.com/zeromicro/go-zero/zrpc"
           "github.com/zeromicro/go-zero/rest"
       )
       
       type Config struct {
           rest.RestConf
           UserRpc zrpc.RpcClientConf
       }
    
  5. 修改yaml配

    vim etc/order.yaml
    

    yaml文件如下:

    Name: order
    Host: 0.0.0.0
    Port: 8888
    UserRpc:
      Etcd:
        Hosts:
        - 127.0.0.1:2379
        Key: user.rpc
    
  6. 完善服务依赖

     vim internal/svc/servicecontext.go
    

    servicecontext.go文件如下:

    package svc
    
    import (
        "zzh.com/microservice/order/api/internal/config"
        "zzh.com/microservice/user/rpc/user"
    
        "github.com/zeromicro/go-zero/zrpc"
    )
    
    type ServiceContext struct {
        Config  config.Config
        UserRpc user.User
    }
    
    func NewServiceContext(c config.Config) *ServiceContext {
        return &ServiceContext{
            Config:  c,
            UserRpc: user.NewUser(zrpc.MustNewClient(c.UserRpc)),
        }
    }
    
  7. 添加order演示逻辑

    修改getorderlogic.go文件

     vim internal/logic/getorderlogic.go
    

    getorderlogic文件如下:

     package logic
     
     import (
         "context"
         "errors"
     
         "zzh.com/microservice/order/api/internal/svc"
         "zzh.com/microservice/order/api/internal/types"
         "zzh.com/microservice/user/rpc/types/user"
     
         "github.com/zeromicro/go-zero/core/logx"
     )
     
     type GetOrderLogic struct {
         logx.Logger
         ctx    context.Context
         svcCtx *svc.ServiceContext
     }
     
     func NewGetOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) GetOrderLogic {
         return GetOrderLogic{
             Logger: logx.WithContext(ctx),
             ctx:    ctx,
             svcCtx: svcCtx,
         }
     }
     
     func (l *GetOrderLogic) GetOrder(req *types.OrderReq) (*types.OrderReply, error) {
         user, err := l.svcCtx.UserRpc.GetUser(l.ctx, &user.IdRequest{
             Id: "1",
         })
         if err != nil {
             return nil, err
         }
     
         if user.Name != "test" {
             return nil, errors.New("用户不存在")
         }
     
         return &types.OrderReply{
             Id:   req.Id,
             Name: "test order",
         }, nil
     }
    

5.3 启动服务并验证

  1. 启动etcd

     etcd
    
  2. 下载依赖

     go mod tidy
    
  3. 启动user rpc

    # 在 mall/user/rpc 目录
    $ go run user.go -f etc/user.yaml
    Starting rpc server at 127.0.0.1:8080...
    
  4. 启动order api

    # 在 mall/order/api 目录
    $ go run order.go -f etc/order.yaml
    Starting server at 0.0.0.0:8888...
    
  5. 访问order api

     $ curl -i -X GET http://localhost:8888/api/order/get/1
    HTTP/1.1 200 OK
    Content-Type: application/json
    Date: Sun, 07 Feb 2021 03:45:05 GMT
    Content-Length: 30
    
    {"id":"1","name":"test order"}
    
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值