前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用go-zero快速构建支持高并发的微服务

使用go-zero快速构建支持高并发的微服务

作者头像
杨永贞
发布2020-09-02 16:31:32
2.1K0
发布2020-09-02 16:31:32
举报

0. 为什么说做好微服务很难?

要想做好微服务,我们需要理解和掌握的知识点非常多,从几个维度上来说:

  • 基本功能层面
    1. 并发控制&限流,避免服务被突发流量击垮
    2. 服务注册与服务发现,确保能够动态侦测增减的节点
    3. 负载均衡,需要根据节点承受能力分发流量
    4. 超时控制,避免对已超时请求做无用功
    5. 熔断设计,快速失败,保障故障节点的恢复能力
  • 高阶功能层面
    1. 请求认证,确保每个用户只能访问自己的数据
    2. 链路追踪,用于理解整个系统和快速定位特定请求的问题
    3. 日志,用于数据收集和问题定位
    4. 可观测性,没有度量就没有优化

对于其中每一点,我们都需要用很长的篇幅来讲述其原理和实现,那么对我们后端开发者来说,要想把这些知识点都掌握并落实到业务系统里,难度是非常大的,不过我们可以依赖已经被大流量验证过的框架体系。go-zero 微服务框架就是为此而生。

另外,我们始终秉承工具大于约定和文档的理念。我们希望尽可能减少开发人员的心智负担,把精力都投入到产生业务价值的代码上,减少重复代码的编写,所以我们开发了goctl工具。

下面我通过短链微服务来演示通过go-zero快速的创建微服务的流程,走完一遍,你就会发现:原来编写微服务如此简单!

1. 什么是短链服务?

短链服务就是将长的 URL 网址,通过程序计算等方式,转换为简短的网址字符串。

写此短链服务是为了从整体上演示 go-zero 构建完整微服务的过程,算法和实现细节尽可能简化了,所以这不是一个高阶的短链服务。

2. 短链微服务架构图

  • 这里把 shorten 和 expand 分开为两个微服务,并不是说一个远程调用就需要拆分为一个微服务,只是为了最简演示多个微服务而已
  • 后面的 redis 和 mysql 也是共用的,但是在真正项目里要尽可能每个微服务使用自己的数据库,数据边界要清晰

3. 准备工作

  • 安装 etcd, mysql, redis
  • 准备 goctl 工具
  • 直接从https://github.com/tal-tech/go-zero/releases下载最新版,后续会加上自动更新
    • 也可以从源码编译,在任意目录下进行,目的是为了编译 goctl 工具

1. git clone https://github.com/tal-tech/go-zero 2. 在tools/goctl目录下编译 goctl 工具go build goctl.go 3. 将生成的 goctl 放到$PATH下,确保 goctl 命令可运行

  • 创建工作目录shorturl
  • shorturl目录下执行go mod init shorturl初始化go.mod

4. 编写 API Gateway 代码

  • 通过 goctl 生成shorturl.api并编辑,为了简洁,去除了文件开头的info,代码如下:
type (
  shortenReq struct {
      url string `form:"url"`
  }

  shortenResp struct {
      shortUrl string `json:"shortUrl"`
  }
)

type (
  expandReq struct {
      key string `form:"key"`
  }

  expandResp struct {
      url string `json:"url"`
  }
)

service shorturl-api {
  @server(
      handler: ShortenHandler
  )
  get /shorten(shortenReq) returns(shortenResp)

  @server(
      handler: ExpandHandler
  )
  get /expand(expandReq) returns(expandResp)
}

type 用法和 go 一致,service 用来定义 get/post/head/delete 等 api 请求,解释如下:

  • service shorturl-api {这一行定义了 service 名字
  • @server部分用来定义 server 端用到的属性
  • handler定义了服务端 handler 名字
  • get /shorten(shortenReq) returns(shortenResp)定义了 get 方法的路由、请求参数、返回参数等
    • 使用 goctl 生成 API Gateway 代码
goctl api go -api shorturl.api -dir api

生成的文件结构如下:

.
├── api
│   ├── etc
│   │   └── shorturl-api.yaml         // 配置文件
│   ├── internal
│   │   ├── config
│   │   │   └── config.go             // 定义配置
│   │   ├── handler
│   │   │   ├── expandhandler.go      // 实现expandHandler
│   │   │   ├── routes.go             // 定义路由处理
│   │   │   └── shortenhandler.go     // 实现shortenHandler
│   │   ├── logic
│   │   │   ├── expandlogic.go        // 实现ExpandLogic
│   │   │   └── shortenlogic.go       // 实现ShortenLogic
│   │   ├── svc
│   │   │   └── servicecontext.go     // 定义ServiceContext
│   │   └── types
│   │       └── types.go              // 定义请求、返回结构体
│   └── shorturl.go                   // main入口定义
├── go.mod
├── go.sum
└── shorturl.api
  • 启动 API Gateway 服务,默认侦听在 8888 端口
go run api/shorturl.go -f api/etc/shorturl-api.yaml
  • 测试 API Gateway 服务
curl -i "http://localhost:8888/shorten?url=http://www.xiaoheiban.cn"

返回如下:

HTTP/1.1 200 OK
Content-Type: application/json
Date: Thu, 27 Aug 2020 14:31:39 GMT
Content-Length: 15

{"shortUrl":""}

可以看到我们 API Gateway 其实啥也没干,就返回了个空值,接下来我们会在 rpc 服务里实现业务逻辑

  • 可以修改internal/svc/servicecontext.go来传递服务依赖(如果需要)
  • 实现逻辑可以修改internal/logic下的对应文件
  • 可以通过goctl生成各种客户端语言的 api 调用代码
  • 到这里,你已经可以通过 goctl 生成客户端代码给客户端同学并行开发了,支持多种语言,详见文档

5. 编写 shorten rpc 服务

  • rpc/shorten目录下编写shorten.proto文件

可以通过命令生成 proto 文件模板

goctl rpc template -o shorten.proto

修改后文件内容如下:

syntax = "proto3";

package shorten;

message shortenReq {
    string url = 1;
}

message shortenResp {
    string key = 1;
}

service shortener {
    rpc shorten(shortenReq) returns(shortenResp);
}
  • goctl生成 rpc 代码,在rpc/shorten目录下执行命令
goctl rpc proto -src shorten.proto

文件结构如下:

rpc/shorten
├── etc
│   └── shorten.yaml               // 配置文件
├── internal
│   ├── config
│   │   └── config.go              // 配置定义
│   ├── logic
│   │   └── shortenlogic.go        // rpc业务逻辑在这里实现
│   ├── server
│   │   └── shortenerserver.go     // 调用入口, 不需要修改
│   └── svc
│       └── servicecontext.go      // 定义ServiceContext,传递依赖
├── pb
│   └── shorten.pb.go
├── shorten.go                     // rpc服务main函数
├── shorten.proto
└── shortener
    ├── shortener.go               // 提供了外部调用方法,无需修改
    ├── shortener_mock.go          // mock方法,测试用
    └── types.go                   // request/response结构体定义

直接可以运行,如下:

$ go run shorten.go -f etc/shorten.yaml
Starting rpc server at 127.0.0.1:8080...

etc/shorten.yaml文件里可以修改侦听端口等配置

6. 编写 expand rpc 服务

  • rpc/expand目录下编写expand.proto文件

可以通过命令生成 proto 文件模板

goctl rpc template -o expand.proto

修改后文件内容如下:

syntax = "proto3";

package expand;

message expandReq {
    string key = 1;
}

message expandResp {
    string url = 1;
}

service expander {
    rpc expand(expandReq) returns(expandResp);
}
  • goctl生成 rpc 代码,在rpc/expand目录下执行命令
goctl rpc proto -src expand.proto

文件结构如下:

rpc/expand
├── etc
│   └── expand.yaml                // 配置文件
├── expand.go                      // rpc服务main函数
├── expand.proto
├── expander
│   ├── expander.go                // 提供了外部调用方法,无需修改
│   ├── expander_mock.go           // mock方法,测试用
│   └── types.go                   // request/response结构体定义
├── internal
│   ├── config
│   │   └── config.go              // 配置定义
│   ├── logic
│   │   └── expandlogic.go         // rpc业务逻辑在这里实现
│   ├── server
│   │   └── expanderserver.go      // 调用入口, 不需要修改
│   └── svc
│       └── servicecontext.go      // 定义ServiceContext,传递依赖
└── pb
    └── expand.pb.go

修改etc/expand.yaml里面的ListenOn的端口为8081,因为8080已经被shorten服务占用了

修改后运行,如下:

$ go run expand.go -f etc/expand.yaml
Starting rpc server at 127.0.0.1:8081...

etc/expand.yaml文件里可以修改侦听端口等配置

7. 修改 API Gateway 代码调用 shorten/expand rpc 服务

  • 修改配置文件shorter-api.yaml,增加如下内容
Shortener:
  Etcd:
    Hosts:
      - localhost:2379
    Key: shorten.rpc
Expander:
  Etcd:
    Hosts:
      - localhost:2379
    Key: expand.rpc

通过 etcd 自动去发现可用的 shorten/expand 服务

  • 修改internal/config/config.go如下,增加 shorten/expand 服务依赖
type Config struct {
  rest.RestConf
  Shortener rpcx.RpcClientConf     // 手动代码
  Expander  rpcx.RpcClientConf     // 手动代码
}
  • 修改internal/svc/servicecontext.go,如下:
type ServiceContext struct {
  Config    config.Config
  Shortener rpcx.Client                                 // 手动代码
  Expander  rpcx.Client                                 // 手动代码
}

func NewServiceContext(config config.Config) *ServiceContext {
  return &ServiceContext{
      Config:    config,
      Shortener: rpcx.MustNewClient(config.Shortener),    // 手动代码
      Expander:  rpcx.MustNewClient(config.Expander),     // 手动代码
  }
}

通过 ServiceContext 在不同业务逻辑之间传递依赖

  • 修改internal/logic/expandlogic.go,如下:
type ExpandLogic struct {
  ctx context.Context
  logx.Logger
  expander rpcx.Client            // 手动代码
}

func NewExpandLogic(ctx context.Context, svcCtx *svc.ServiceContext) ExpandLogic {
  return ExpandLogic{
      ctx:    ctx,
      Logger: logx.WithContext(ctx),
      expander: svcCtx.Expander,    // 手动代码
  }
}

func (l *ExpandLogic) Expand(req types.ExpandReq) (*types.ExpandResp, error) {
  // 手动代码开始
  resp, err := expander.NewExpander(l.expander).Expand(l.ctx, &expander.ExpandReq{
      Key: req.Key,
  })
  if err != nil {
      return nil, err
  }

  return &types.ExpandResp{
      Url: resp.Url,
  }, nil
  // 手动代码结束
}

增加了对expander服务的依赖,并通过调用expanderExpand方法实现短链恢复到 url

  • 修改internal/logic/shortenlogic.go,如下:
type ShortenLogic struct {
  ctx context.Context
  logx.Logger
  shortener rpcx.Client             // 手动代码
}

func NewShortenLogic(ctx context.Context, svcCtx *svc.ServiceContext) ShortenLogic {
  return ShortenLogic{
      ctx:    ctx,
      Logger: logx.WithContext(ctx),
      shortener: svcCtx.Shortener,    // 手动代码
  }
}

func (l *ShortenLogic) Shorten(req types.ShortenReq) (*types.ShortenResp, error) {
  // 手动代码开始
  resp, err := shortener.NewShortener(l.shortener).Shorten(l.ctx, &shortener.ShortenReq{
      Url: req.Url,
  })
  if err != nil {
      return nil, err
  }

  return &types.ShortenResp{
      ShortUrl: resp.Key,
  }, nil
  // 手动代码结束
}

增加了对shortener服务的依赖,并通过调用shortenerShorten方法实现 url 到短链的变换

至此,API Gateway 修改完成,虽然贴的代码多,但是期中修改的是很少的一部分,为了方便理解上下文,我贴了完整代码,接下来处理 CRUD+cache

8. 定义数据库表结构,并生成 CRUD+cache 代码

  • shorturl 下创建 rpc/model 目录:mkdir -p rpc/model
  • 在 rpc/model 目录下编写创建 shorturl 表的 sql 文件shorturl.sql,如下:
CREATE TABLE `shorturl`
(
  `shorten` varchar(255) NOT NULL COMMENT 'shorten key',
  `url` varchar(255) NOT NULL COMMENT 'original url',
  PRIMARY KEY(`shorten`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • 创建 DB 和 table
create database gozero;
source shorturl.sql;
  • rpc/model目录下执行如下命令生成 CRUD+cache 代码,-c表示使用redis cache
goctl model mysql ddl -c -src shorturl.sql -dir .

也可以用datasource命令代替ddl来指定数据库链接直接从 schema 生成

生成后的文件结构如下:

rpc/model
├── shorturl.sql
├── shorturlmodel.go              // CRUD+cache代码
└── vars.go                       // 定义常量和变量

9. 修改 shorten/expand rpc 代码调用 crud+cache 代码

  • 修改rpc/expand/etc/expand.yaml,增加如下内容:
DataSource: root:@tcp(localhost:3306)/gozero
Table: shorturl
Cache:
  - Host: localhost:6379

可以使用多个 redis 作为 cache,支持 redis 单点或者 redis 集群

  • 修改rpc/expand/internal/config.go,如下:
type Config struct {
  rpcx.RpcServerConf
  DataSource string             // 手动代码
  Table      string             // 手动代码
  Cache      cache.CacheConf    // 手动代码
}

增加了 mysql 和 redis cache 配置

  • 修改rpc/expand/internal/svc/servicecontext.go,如下:
type ServiceContext struct {
  c     config.Config
  Model *model.ShorturlModel   // 手动代码
}

func NewServiceContext(c config.Config) *ServiceContext {
  return &ServiceContext{
      c:     c,
      Model: model.NewShorturlModel(sqlx.NewMysql(c.DataSource), c.Cache, c.Table), // 手动代码
  }
}
  • 修改rpc/expand/internal/logic/expandlogic.go,如下:
type ExpandLogic struct {
  ctx context.Context
  logx.Logger
  model *model.ShorturlModel          // 手动代码
}

func NewExpandLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExpandLogic {
  return &ExpandLogic{
      ctx:    ctx,
      Logger: logx.WithContext(ctx),
      model:  svcCtx.Model,             // 手动代码
  }
}

func (l *ExpandLogic) Expand(in *expand.ExpandReq) (*expand.ExpandResp, error) {
  // 手动代码开始
  res, err := l.model.FindOne(in.Key)
  if err != nil {
      return nil, err
  }

  return &expand.ExpandResp{
      Url: res.Url,
  }, nil
  // 手动代码结束
}
  • 修改rpc/shorten/etc/shorten.yaml,增加如下内容:
DataSource: root:@tcp(localhost:3306)/gozero
Table: shorturl
Cache:
  - Host: localhost:6379

可以使用多个 redis 作为 cache,支持 redis 单点或者 redis 集群

  • 修改rpc/shorten/internal/config.go,如下:
type Config struct {
  rpcx.RpcServerConf
  DataSource string            // 手动代码
  Table      string            // 手动代码
  Cache      cache.CacheConf   // 手动代码
}

增加了 mysql 和 redis cache 配置

  • 修改rpc/shorten/internal/svc/servicecontext.go,如下:
type ServiceContext struct {
  c     config.Config
  Model *model.ShorturlModel   // 手动代码
}

func NewServiceContext(c config.Config) *ServiceContext {
  return &ServiceContext{
      c:     c,
      Model: model.NewShorturlModel(sqlx.NewMysql(c.DataSource), c.Cache, c.Table), // 手动代码
  }
}
  • 修改rpc/shorten/internal/logic/shortenlogic.go,如下:
const keyLen = 6

type ShortenLogic struct {
  ctx context.Context
  logx.Logger
  model *model.ShorturlModel          // 手动代码
}

func NewShortenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShortenLogic {
  return &ShortenLogic{
      ctx:    ctx,
      Logger: logx.WithContext(ctx),
      model:  svcCtx.Model,             // 手动代码
  }
}

func (l *ShortenLogic) Shorten(in *shorten.ShortenReq) (*shorten.ShortenResp, error) {
  // 手动代码开始,生成短链接
  key := hash.Md5Hex([]byte(in.Url))[:keyLen]
  _, err := l.model.Insert(model.Shorturl{
      Shorten: key,
      Url:     in.Url,
  })
  if err != nil {
      return nil, err
  }

  return &shorten.ShortenResp{
      Key: key,
  }, nil
  // 手动代码结束
}

至此代码修改完成,凡事手动修改的代码我加了标注

10. 完整调用演示

  • shorten api 调用
~ curl -i "http://localhost:8888/shorten?url=http://www.xiaoheiban.cn"

返回如下:

HTTP/1.1 200 OK
Content-Type: application/json
Date: Sat, 29 Aug 2020 10:49:49 GMT
Content-Length: 21

{"shortUrl":"f35b2a"}
  • expand api 调用
curl -i "http://localhost:8888/expand?key=f35b2a"

返回如下:

HTTP/1.1 200 OK
Content-Type: application/json
Date: Sat, 29 Aug 2020 10:51:53 GMT
Content-Length: 34

{"url":"http://www.xiaoheiban.cn"}

11. Benchmark

因为写入依赖于 mysql 的写入速度,就相当于压 mysql 了,所以压测只测试了 expand 接口,相当于从 mysql 里读取并利用缓存,shorten.lua 里随机从 db 里获取了 100 个热 key 来生成压测请求

可以看出在我的 MacBook Pro 上能达到 3 万 + 的 qps。

12. 总结

我们一直强调工具大于约定和文档

go-zero 不只是一个框架,更是一个建立在框架 + 工具基础上的,简化和规范了整个微服务构建的技术体系。

我们在保持简单的同时也尽可能把微服务治理的复杂度封装到了框架内部,极大的降低了开发人员的心智负担,使得业务开发得以快速推进。

通过 go-zero+goctl 生成的代码,包含了微服务治理的各种组件,包括:并发控制、自适应熔断、自适应降载、自动缓存控制等,可以轻松部署以承载巨大访问量。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-08-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 0. 为什么说做好微服务很难?
  • 1. 什么是短链服务?
  • 2. 短链微服务架构图
  • 3. 准备工作
  • 4. 编写 API Gateway 代码
  • 5. 编写 shorten rpc 服务
  • 6. 编写 expand rpc 服务
  • 7. 修改 API Gateway 代码调用 shorten/expand rpc 服务
  • 8. 定义数据库表结构,并生成 CRUD+cache 代码
  • 9. 修改 shorten/expand rpc 代码调用 crud+cache 代码
  • 10. 完整调用演示
  • 11. Benchmark
  • 12. 总结
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档