Featured image of post go-zero

go-zero

go 最流行最强大的微服务框架

GitHub

官网

go-zero(收录于 CNCF 云原生技术全景图:https://landscape.cncf.io/?selected=go-zero)是一个集成了各种工程实践的 web 和 rpc 框架。通过弹性设计保障了大并发服务端的稳定性,经受了充分的实战检验。

go-zero 包含极简的 API 定义和生成工具 goctl,可以根据定义的 api 文件一键生成 Go, iOS, Android, Kotlin, Dart, TypeScript, JavaScript 代码,并可直接运行。

使用 go-zero 的好处:

  • 轻松获得支撑千万日活服务的稳定性
  • 内建级联超时控制、限流、自适应熔断、自适应降载等微服务治理能力,无需配置和额外代码
  • 微服务治理中间件可无缝集成到其它现有框架使用
  • 极简的 API 描述,一键生成各端代码
  • 自动校验客户端请求参数合法性
  • 大量微服务治理和并发工具包

环境准备

Goctl

goctl是go-zero微服务框架下的代码生成工具。使用 goctl 可显著提升开发效率,让开发人员将时间重点放在业务开发上,其功能有:

  • api服务生成
  • rpc服务生成
  • model代码生成
  • 模板管理

安装

$ go install github.com/zeromicro/go-zero/tools/goctl@latest

命令

goctl-cn-ce8593be6eca578a0fc864abb9369bc9

  • $ goctl -v 查看版本信息
api 指令

goctl api是goctl中的核心模块之一,其可以通过.api文件一键快速生成一个api服务

其中的结构体编写,路由定义用api进行替代,因此总的来说,省去的是你创建文件夹、添加各种文件及资源依赖的过程的时间。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$ goctl api -h                   
Generate api related files

Usage:
  goctl api [flags]
  goctl api [command]

Available Commands:
  dart        Generate dart files for provided api in api file
  doc         Generate doc files
  format      Format api files
  go          Generate go files for provided api in yaml file
  java        Generate java files for provided api in api file
  kt          Generate kotlin code for provided api file
  new         Fast create api service
  plugin      Custom file generator
  ts          Generate ts files for provided api in api file
  validate    Validate api file

Flags:
      --branch string   The branch of the remote repo, it does work with --remote (default "master")
  -h, --help            help for api
      --home string     The goctl home path of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
      --o string        Output a sample api file
      --remote string   The remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
                                The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure

Use "goctl api [command] --help" for more information about a command.
生成api模板文件

$ goctl api -o example.api

根据提供的api生成go文件

$ goctl api go -api example.api -dir .

  • –api:提供的api文件地址
  • –dir:输出目标目录
  • –style:文件的命名格式 详见
rpc 指令

goctl rpc是goctl脚手架下的一个rpc服务代码生成模块,支持proto模板生成和rpc服务代码生成,通过此工具生成代码你只需要关注业务逻辑编写而不用去编写一些重复性的代码。这使得我们把精力重心放在业务上,从而加快了开发效率且降低了代码出错率。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$ goctl rpc -h
Generate rpc code

Usage:
  goctl rpc [flags]
  goctl rpc [command]

Available Commands:
  new         Generate rpc demo service
  protoc      Generate grpc code
  template    Generate proto template

Flags:
      --branch string   The branch of the remote repo, it does work with --remote
  -h, --help            help for rpc
      --home string     The goctl home path of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
      --o string        Output a sample proto file
      --remote string   The remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
                                The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure

Use "goctl rpc [command] --help" for more information about a command.
生成proto模板

$ goctl rpc template -o example.proto

生成rpc服务代码

$ goctl rpc protoc example.proto --go_out=. --go-grpc_out=. --zrpc_out=.

model 指令

goctl model 为go-zero下的工具模块中的组件之一,目前支持识别mysql ddl进行model层代码生成,通过命令行或者idea插件(即将支持)可以有选择地生成带redis cache或者不带redis cache的代码逻辑。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$ goctl model -h
Generate model code

Usage:
  goctl model [command]

Available Commands:
  mongo       Generate mongo model
  mysql       Generate mysql model
  pg          Generate postgresql model

Flags:
  -h, --help   help for model

Use "goctl model [command] --help" for more information about a command.
template 指令

模板(Template)是数据驱动生成的基础,所有的代码(rest api、rpc、model、docker、kube)生成都会依赖模板, 默认情况下,模板生成器会选择内存中的模板进行生成,而对于有模板修改需求的开发者来讲,则需要将模板进行落盘, 从而进行模板修改,在下次代码生成时会加载指定路径下的模板进行生成。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$ goctl template -h
Template operation

Usage:
  goctl template [command]

Available Commands:
  clean       Clean the all cache templates
  init        Initialize the all templates(force update)
  revert      Revert the target template to the latest
  update      Update template of the target category to the latest

Flags:
  -h, --help   help for template

Use "goctl template [command] --help" for more information about a command.
通过ddl生成

$ goctl model mysql ddl -src="./*.sql" -dir="./sql/model" -c

通过datasource生成

$ goctl model mysql datasource -url="user:password@tcp(127.0.0.1:3306)/database" -table="*" -dir="./model"

docker 指令

goctl docker 可以极速生成一个 Dockerfile,帮助开发/运维人员加快部署节奏,降低部署复杂度。

$ goctl docker -go hello.go

  • –go:包含主函数的文件
  • –port:要公开的端口,默认为无
  • –tz:容器的时区
  • –version:golang镜像的版本
kube 指令

goctl kube提供了快速生成一个 k8s 部署文件的功能,可以加快开发/运维人员的部署进度,减少部署复杂度。

$ goctl kube deploy -name redis -namespace adhoc -image redis:6-alpine -o redis.yaml -port 6379

  • –remote:模板的远程git repo
  • –branch:远程repo的分支
  • –home:模板的goctl首页路径
  • –name:部署的名称
  • –namespace:部署的命名空间
  • –image:部署的docker镜像
  • –nodePort:要公开的部署的nodePort(默认为0)
  • –port:要在pod上监听的部署的端口(默认为0)
  • –limitCpu:部署的cpu上线(默认为1000)
  • –limitMem:部署的内存上线(默认为1024)
  • –maxReplicas:部署的最大复制数(默认为0)
  • –minReplicas:部署的最小复制量(默认为3)
  • –replicas:要部署的副本数量(默认为3)
  • –requestCpu:要部署的请求cpu(默认为500)
  • –requestMem:要部署的请求内存(默认为512)
  • –revisions:限制修订历史的数量(默认为5)
  • –secret:从注册表中提取镜像的秘密
  • –serviceAccount:部署的ServiceAccount
  • -o:输出的yaml文件

protoc

protoc是一款用C++编写的工具,其可以将proto文件翻译为指定语言的代码。在go-zero的微服务中,我们采用grpc进行服务间的通信,而grpc的编写就需要用到protoc和翻译成go语言rpc stub代码的插件protoc-gen-go。

安装

方式一:goctl一键安装

$ goctl env check -i -f --verbose

方式二:源文件安装
  • 进入protobuf release 页面,选择适合自己操作系统的压缩包文件

  • 解压protoc-x.x.x-osx-x86_64.zip并进入protoc-x.x.x-osx-x86_64

    $ cd protoc-x.x.x-osx-x86_64/bin

    复制

  • 将启动的protoc二进制文件移动到被添加到环境变量的任意path下,如$GOPATH/bin,这里不建议直接将其和系统的以下path放在一起。

    $ mv protoc $GOPATH/bin

    复制

    :::tip $GOPATH为你本机的实际文件夹地址 :::

  • 验证安装结果

    $ protoc --version

    libprotoc x.x.x

  • 下载安装protoc-gen-go

    1
    2
    
    $ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
    $ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
    

组件

logx

使用zap

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import (
	"context"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/zero-contrib/logx/zapx"
)

func main() {
	writer, err := zapx.NewZapWriter()
	logx.Must(err)
	logx.SetWriter(writer)

	logx.Infow("infow foo",
		logx.Field("url", "http://localhost:8080/hello"),
		logx.Field("attempt", 3),
		logx.Field("backoff", time.Second),
	)
	logx.Errorw("errorw foo",
		logx.Field("url", "http://localhost:8080/hello"),
		logx.Field("attempt", 3),
		logx.Field("backoff", time.Second),
	)
	logx.Sloww("sloww foo",
		logx.Field("url", "http://localhost:8080/hello"),
		logx.Field("attempt", 3),
		logx.Field("backoff", time.Second),
	)
	logx.Error("error")
	logx.Infov(map[string]interface{}{
		"url":     "localhost:8080/hello",
		"attempt": 3,
		"backoff": time.Second,
		"value":   "foo",
	})
	logx.WithDuration(1100*time.Microsecond).Infow("infow withduration",
		logx.Field("url", "localhost:8080/hello"),
		logx.Field("attempt", 3),
		logx.Field("backoff", time.Second),
	)
	logx.WithContext(context.Background()).WithDuration(1100*time.Microsecond).Errorw(
		"errorw withcontext withduration",
		logx.Field("url", "localhost:8080/hello"),
		logx.Field("attempt", 3),
		logx.Field("backoff", time.Second),
	)
	logx.WithDuration(1100*time.Microsecond).WithContext(context.Background()).Errorw(
		"errorw withduration withcontext",
		logx.Field("url", "localhost:8080/hello"),
		logx.Field("attempt", 3),
		logx.Field("backoff", time.Second),
	)
}

开发

API

语法介绍

渝ICP备2022001449号
本站总访问量