Go语言-框架三件套(Gorm、Kitex、Hertz )介绍 | 青训营笔记

125 阅读2分钟

这是我参与「第五届青训营 」笔记创作活动的第 3 天

前言

本文主要介绍:

GO语言框架三件套Gorm、Kitex、Hertz的概念和使用

01.Gorm

概念:

Gorm是一个已经迭代了10年+的功能强大的ORM框架,在字节内部被广泛使用并且拥有非常丰富的,具有高易用性、高性能、高扩展性特点。

使用注意:

Gorm的约定(默认)

Gorm使用名为ID的字段作为主键

使用结构体的蛇形负数作为表名

字段名的蛇形作为列名

使用CreatedAt、UpdatedAt字段作为创建、更新时间

02.Kitex

概念:

Kitex是字节内部的Golang 微服务RPC框架,具有高性能、强可扩展的主要特点,支持多协议并且开源扩展。

使用注意:

创建Client

import "example/kitex_gen/api/echo"

import "github . com/ cloudwego/kitex/client"
...
c, err := echo.NewClient("example", client.WithHostPorts("0.0.0.0:8888"))
if err != nil {
    log . Fatal(err)
}

发起请求

import "example/kitex_gen/ api"
...
req := &api . Request{Message: "my request"}
resp,err := c.Echo(context. Background(),req,callopt.WithRPCTimeout(3*time . Second))
if err != nil {
    log .Fatal(err)
}
log .Println(resp)

03.Hertz

概念:

Hertz是字节内部的HTTP框架,参考了其他开源框架的优势,结合字节跳动内部的需求拥有丰富的开源扩展。 它是一个超大规模的企业级微服务 HTTP 框架,具有简单易用、易扩展、低时延等特点。最初,字节跳动内部的 HTTP 框架是对 Gin 框架的封装,它具备不错的易用性,生态也较为完善。随着内部业务的不断发展,业务对高性能、多场景的需求日渐强烈,而 Gin 是对 Golang 原生 net/http 进行的二次开发,在按需扩展和性能优化上受到很大局限。

为了满足业务需求,更好地服务各大业务线,2020 年初,基础架构服务框架团队基于对内部使用场景的认知,结合对外部主流开源 HTTP 框架 Fasthttp、Gin、Echo 的调研,开始开发内部框架 Hertz,使之有更好的性能及稳定性表现,既能满足字节业务发展,又能应对不断演进的技术需求。

使用注意:

Hertz Client中Hertz提供了HTTP Client用于帮助用户发送HTTP请求

c, err := client.Newclient()
if err != nil {
    return
// send http get request
status,body- := c.Get(context.Background(),dst: nil,url:"http:.l/www.example.com")
fmt.Printf( format: "status=%v body=%v\n", status,string(body))
// send http post request
var postArgs protocol.Args
postArgs.set( key: "arg" ,value: "a" ) l / set post args
statusbody_ = c.Post(context.Background(),dst: nil,url: "http:0lwww.example.com",&postArgs)
fmt.Printf( format: "status=%v body=%v\n", status,string(body))