Go-zero从入门到精通(一)

一、开发环境

开发环境:

  • Go:go version go1.18.6 darwin/arm64
  • goctl:goctl version 1.4.0 darwin/arm64
  • IDE:Goland

安装文档直接看 官网文档


二、微服务项目demo实战

用户在查询订单时,同时需要获取用户信息。

创建项目,一个 order 服务,一个 user 服务

$ mkdir mall
$ cd mall 
$ goctl api new order
$ goctl api new user
$ cd mall
$ go work init
$ go work use order 
$ go work use user

我要实现使用 order 服务调用 user 服务。需要安装一下依赖

$ cd mall/order
$ go mod tidy
$ cd mall/user
$ go mod tidy

所以需要在 user 模块里创建一个 user.proto

$ cd mall/user/rpc
$ vim user.proto

文件内容如下:

// 声明 proto 语法版本,固定值
syntax = "proto3";

// proto 包名
package user;

// 生成 golang 代码后的包名
option go_package = "./user";

// 定义请求体
message IdRequest {
  string id = 1;
}
// 定义响应体
message UserResponse {
  string id = 1;
  string name = 2;
  string gender = 3;
}

// 定义 User 服务
service User{
  rpc getUser(IdRequest) returns(UserResponse);
}

服务和服务之间一般使用 rpc 通信,最常使用的就是 grpc,接下来就是使用 protoc-gen-go 将上述的 proto 文件生成 go 代码。

$ cd mall/user/rpc
$ goctl rpc protoc ./user.proto --go_out=./types --go-grpc_out=./types --zrpc_out=./ --style=go_zero

填充 logic 逻辑

func (l *GetUserLogic) GetUser(in *user.IdRequest) (*user.UserResponse, error) {
	// todo: add your logic here and delete this line

	return &user.UserResponse{
		Id:     in.GetId(),
		Name:   "hello my good",
		Gender: "man",
	}, nil
}

接下来在 order 模块,写一个接口,获取订单信息,其中订单信息中需要携带用户信息。

编写 order.api

$ cd mall/order
$ vim order.api
type Request {
	Name string `path:"name,options=you|me"`
}

type Response {
	Message string `json:"message"`
}

type (
	OrderReq {
		Id string `path:"id"`
	}
	OrderResp {
		Id     string `json:"id"`
		Name   string `json:"Name"`
		Gender string `json:"Gender"`
	}
)

service order-api {
	@handler OrderHandler
	get /from/:name(Request) returns (Response)
	@handler GetOrderHandler
	get /api/user/get/:id(OrderReq) returns (OrderResp)
}

生成 api 服务

$ cd mall/order
$ goctl api go -api order.api -dir=./

新增 user rpc 配置

$ vim mall/order/internal/config/config.go
type Config struct {
    rest.RestConf
    UserRpc zrpc.RpcClientConf
}

在 etc/order-api.yaml

Name: order-api
Host: 0.0.0.0
Port: 8888
UserRpc:
  Etcd:
    Hosts:
      - 127.0.0.1:2379
    Key: user.rpc

创建对 user 服务的rpc调用,order/internal/svc/servicecontext.go

package svc

import (
	"github.com/zeromicro/go-zero/zrpc"
	"order/internal/config"
	"user/rpc/userclient"
)

type ServiceContext struct {
	Config  config.Config
	UserRpc userclient.User
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config:  c,
		UserRpc: userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),
	}
}

编写 logic

package logic

import (
	"context"
	"user/rpc/types/user"

	"order/internal/svc"
	"order/internal/types"

	"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) (resp *types.OrderResp, err error) {
	userId := l.getOrderById(req.Id)
	// 根据用户id调用rpc服务获取用户信息
	userResp, err := l.svcCtx.UserRpc.GetUser(context.Background(), &user.IdRequest{
		Id: userId,
	})
	if err != nil {
		return nil, err
	}
	return &types.OrderResp{
		Id:     userId,
		Name:   "hello name",
		Gender: userResp.Gender,
	}, nil
}

func (l *GetOrderLogic) getOrderById(id string) string {
	return "1"
}

这样就搞完,可以启动 etcd,再分别启动user服务和order服务

$ cd mall/user/rpc
$ go run user.go -f etc/user.yaml
$ cd mall/order
$ go run order.go -f etc/order-api.yaml

访问 api/order/get/1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
go-zero是一个开源的Go语言框架,它在构建微服务和高并发应用方面具有突破性的优势。其中一个突出的特点就是它整合了masterminds/squirrel,从而实现了优雅的多数据库支持。 masterminds/squirrel是一个流行的SQL查询构建器,它以非常直观和灵活的方式提供了编写SQL查询的功能。而go-zero在此基础上做了进一步的封装和优化,使得使用者能够更加方便地编写和执行SQL查询。 首先,go-zero提供了一组简洁而强大的API,使得构建SQL查询非常容易。开发者只需要按照一定的约定来创建查询参数和条件,然后使用go-zero提供的API来构建查询语句,即可完成复杂的SQL查询。 其次,go-zero还增加了一些高级功能,进一步提升了多数据库查询的灵活性和性能。例如,它支持数据库连接池管理,可以动态调整数据库连接数以适应并发请求;还支持分表分库功能,可以按照一定的规则将数据分散存储在不同的数据库或表中,从而提高查询效率。 最重要的是,go-zero通过内置的代码生成工具,提供了自动化生成数据库访问代码的能力。开发者只需要定义数据表的结构,然后运行代码生成工具,就能够自动生成包含增删改查等一系列数据库操作的代码。这极大地提高了开发效率,减少了出错的机会。 综上所述,go-zero整合了masterminds/squirrel,通过提供简洁强大的API、高级功能和自动化代码生成工具,实现了优雅的多数据库支持。它在微服务和高并发应用场景下的表现突出,为开发者提供了极大的便利和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值