Golang 工程实践 | 青训营笔记

187 阅读8分钟

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

Golang 工程实践

一、语言进阶

并发:多线程程序在一个核CPU 上运行。

并行:多线程程序在多个核CPU 上运行。

Go 可以充分发挥多核优势,高效运行

Goroutine

image.png

协程用户态,轻量级线程,栈 KB 级别。

线程内核态,线程跑多个协程,栈 MB 级别。

⭐通过在函数前添加 go关键字即可创建一个协程

快速打印 hello goroutine: 0 ~ hello goroutine: 4

package main

import (
    "fmt"
    "time"
)

func HelloPrint(i int) {
    println("Hello goroutine : " + fmt.Sprint(i))
}

func HelloGoroutine() {
    for i := 0; i < 5; i++ {
            go func(j int) {
                    HelloPrint(j)
            }(i)
    }

    time.Sleep(time.Second) //保证了子协程在执行完之前,主协程不退出。
}

func main() {
    HelloGoroutine()
}

CSP (Communicating Sequential Process)

⭐ 提倡通过通信共享内存而不是通过共享内存实现通信

image.png

Channel

Channel 是用来传递数据的一个数据结构,可以在两个 Goroutine 之间通过传递一个指定类型的值来同步运行和通讯,Channel 是一个引用类型,通过 make(chan 元素类型, [缓冲大小]创建。

  • 无缓冲通道:make(chan int)
  • 有缓冲通道:make(chan int, 2)
image.png

A 子协程发送0~9数字,B 子协程计算输入数字的平方,主协程输出最后的平方数

package main

func CalcPow() {
    src := make(chan int)
    dest := make(chan int, 3)

    // A子协程
    go func() {
            defer close(src) // 当子协程结束时再关闭,减少资源浪费
            for i := 0; i < 10; i++ {
                    src <- i
            }
    }()

    // B 子协程
    go func() {
            defer close(dest)
            for i := range src {
                    dest <- i * i
            }
    }()

    // 主协程
    // 有缓冲通道可以解决生产和消费速度不均衡带来的效率问题
    for i := range dest {
            println(i)
    }
}

func main() {
	CalcPow()
}

并发安全 Lock

当通过共享内存实现通信时,就会存在多个 Goroutine 操作同一个变量的情况。

Mutex 互斥锁

package main

import (
    "sync"
    "time"
)

var (
    x    int64
    lock sync.Mutex
)

func addWithLock() {
    for i := 0; i < 2000; i++ {
        lock.Lock()
        x += 1
        lock.Unlock()
    }
}

func addWithoutLock() {
    for i := 0; i < 2000; i++ {
        x += 1
    }
}

func Add() {
    x = 0
    for i := 0; i < 10; i++ {
        go addWithoutLock()
    }
    time.Sleep(time.Second)
    println("WithoutLock:", x) // x <= 10 * 2000

    x = 0
    for i := 0; i < 10; i++ {
        go addWithLock()
    }
    time.Sleep(time.Second)
    println("WithLock:", x) // x = 10 * 2000
}

func main() {
    Add()
}

WaitGroup

package main

import "sync"

func hello(i int) {
    println("hello goroutine : ", i)
}

func ManyGoWait() {
    var wg sync.WaitGroup
    wg.Add(5) // 开启五个协程,计数器 + 5
    for i := 0; i < 5; i++ {
            go func(j int) {
                    defer wg.Done() // 计数器 - 1
                    hello(j)
            }(i)
    }

    wg.Wait() // 阻塞直到计数器为0
}

func main() {
    ManyGoWait()
}

二、依赖管理

背景

  • 工程项目不可能基于标准库0~1编码搭建
  • 一些业务逻辑的实现都会通过sdk的方式引入,这是就需要管理依赖库
image.png

依赖管理演进

GOPATH

GOPATHGolang 语言支持的一个环境变量,valueGo 项目的工作区。目录有以下结构:

  • src: 存放 Go 项目的源码
  • pkg:存放编译的中间产物,加快编译速度
  • bin:存放 Go 项目编译生成的二进制文件

弊端:无法实现 package 的多版本控制

image.png

GO Vendor

在项目目录下增加 vender 文件,其中存放了当前项目依赖的副本,所有依赖包副本形式放在 $ProjectRoot/vender。在 Vendor 机制下,如果当前项目存在 Vendor 目录,会优先使用该目录下的依赖,如果依赖不存在,会从 GOPATH 中寻找。

优点:通过每个项目引入一份依赖的副本,解决了多个项目需要同一个 package 依赖的冲突问题。

弊端vendor 无法很好解决依赖包的版本变动问题;更新项目有可能出现依赖冲突,导致编译出错。

image.png

GO Module

  • go.mod:配置文件,描述依赖
  • Proxy:中心仓库管理依赖库
  • go get/mod:本地指令工具

终极目标:定义版本规则和管理项目依赖关系。

依赖配置
go.mod
module github.com/wangkechun/go-by-example // 依赖管理基本单元

go 1.18 // 原生库

// 单元依赖 依赖标识:[Module Path][Version/Pseudo-version]
require (
)
version

语义化版本

  • ${MAJOR}.${MINOR}.${PATCH}——V1.3.0V2.3.0

基于 commit 伪版本

  • vx.0.0-yyyymmddhhmmss-abcdefgh1234—— v0.0.0-20220401081311-c38fb59326b7
indirect

对于没有直接表示的模块会在 go.mod 中加上 // indirect

incompatible
  • 主版本 2+ 模块会在模块路径增加 /vN 后缀
  • 对于没有 go.mod 文件并且主版本 2+ 的依赖,会加上 +incompatible
依赖图
image.png
依赖分发
回源
image.png
Proxy

Go Proxy 是一个服务中点,它会缓存源站中的软件内容,缓存的软件版本不会改变,并且在源站软件删除之后依然可用,从而实现了供 immutabilityaviailable 的依赖分发。使用 Go Proxy 之后。构建时会直接从 Go Proxy 站点拉取依赖。

image.png
变量 GOPRROXY
image.png
工具
go get
后缀含义
@update默认
@none删除依赖
@v1.1.2tag版本,语义版本
@23dfdd5特定的commit
@master分支的最新commit
go mod
命令含义
init默认
download下载模块到本地缓存
tidy增加需要的依赖,删除不需要的依赖

三、测试

image.png

单元测试

单元测试主要包括输入测试单元输出,以及校对单元的概念比较广,包括接口函数模块等;用最后的校对来保证代码的功能与我们的预期相符;单侧一方面可以保证质量,在整体覆盖率足够的情况下,一定程度上既保证了新功能本身的正确性,又未破坏原有代码的正确性。另一方面可以提升效率,在代码有 bug 的情况下,通过编写单测,可以在一个较短周期内定位和修复问题。

image.png

测试规则

  1. 所有测试文件以 _test.go 结尾
  2. func TestXxx(*testing T)
  3. 初始化逻辑放到 TestMain

assert

import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func TestHelloTom(t *testing.T) {
    output := HelloTom()
    expectOutput := "Tom"
    assert.Equal(t, expectOutput, output)    
}

func HelloTom() string {
    return "Tom"
}

/*
run test -> PASS
*/

覆盖率

  • 衡量代码是否经过了足够的测试
  • 评价项目的测试水准
  • 评估项目是否达到了高水准测试等级
func TestJudgePassLineTrue(t *testing.T) {
    isPass := JudgePassLine(70)
    assert.Equal(t, true, isPass)
}

func TestJudgePassLineFail(t *testing.T) {
    isPass := JudgePassLine(50)
    assert.Equal(t, false, isPass)
}

func JudgePassLine(score int16) bool {
    if score >= 60 {
            return true
    }
    return false
}
  • 一般覆盖率:50%~60%,较高覆盖率80%+。
  • 测试分支相互独立,全面覆盖。
  • 测试单元粒度足够小,函数单一职责。

依赖

image.png
  • 稳定:相互隔离,能在任何时间,任何环境运行测试。
  • 幂等:每一次测试运行都应该产生与之前一样的结果。

文件处理

func ReadFirstLine() string {
    open, err := os.Open("log")
    /*
    line11
    line22
    line33
    line44
    line55
    */
    defer open.Close()
    if err != nil {
            return ""
    }
    scanner := bufio.NewScanner(open)
    for scanner.Scan() {
            return scanner.Text()
    }
    return ""
}

func ProcessFirstLine() string {
    line := ReadFirstLine()
    destLine := strings.ReplaceAll(line, "11", "00")
    return destLine
}

func TestProcessFirstLine(t *testing.T) {
    firstLine := ProcessFirstLine()
    assert.Equal(t, "line00", firstLine)
}

这个例子的单元测试需要依赖本地文件,如果文件被修改或删除,测试就会 fail。为了保证测试 case 的稳定性,我们对读取文件函数进行 mock,屏蔽对于文件的依赖。

Mock 测试

Monkey: 开源的 mock 测试库,可以对 method或者实例的方法进行 mock

Mockey Patch 的作用域在 Runtime,在运行时通过 Gounsafe 包,能够将内存中函数的地址替换为运行时函数的地址。,跳转到待打桩函数或方法的实现。

快速 Mock 函数:为一个函数或方法打桩。

func TestProcessFirstLineWithMock(t *testing.T) {
    monkey.Patch(ReadFirstLine, func() string {
            return "line110"
    })
    defer monkey.Unpatch(ReadFirstLine)
    line := ProcessFirstLine()
    assert.Equal(t, "line000", line)
}

通过 patchReadfineline 进行打桩 mock,默认返回 line110,再通过 defer 卸载 mock,这样整个测试函数就拜托了本地文件的束缚和依赖。

基准测试

基准测试测试一段程序的运行性能及耗费 CPU 的程度。

  • 优化代码,需要对当前代码分析。
  • 内置的测试框架提供了基准测试的能力。
  • func BenchmarkXxx(*testing B)
// load_balance_selector.go
package benchmark

import (
    "github.com/bytedance/gopkg/lang/fastrand"
    "math/rand"
)

var ServerIndex [10]int

func InitServerIndex() {
    for i := 0; i < 10; i++ {
            ServerIndex[i] = i+100
    }
}

func Select() int {
    return ServerIndex[rand.Intn(10)]
}

func FastSelect() int {
    return ServerIndex[fastrand.Intn(10)]
}

//load_balance_selector_test.go
package benchmark

import (
    "testing"
)

// 串行
func BenchmarkSelect(b *testing.B) {
    InitServerIndex()
    b.ResetTimer() // InitServerIndex() 的时间不包含在内
    for i := 0; i < b.N; i++ {
            Select()
    }
}

// 并行
func BenchmarkSelectParallel(b *testing.B) {
    InitServerIndex()
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
            for pb.Next() {
                    Select()
            }
    })
}
func BenchmarkFastSelectParallel(b *testing.B) {
    InitServerIndex()
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
            for pb.Next() {
                    FastSelect()
            }
    })
}
image.png

四、项目实战

需求设计

需求背景

掘金社区话题页面,页面的功能包括话题详情回帖列表支持回帖点赞回帖回复,以此为需求模型,开发一个该页面交互涉及的服务端小功能。

需求描述

展示话题(标题,文字描述)和回帖列表

暂不考虑前端页面实现,仅仅实现一个本地 web 服务

话题和回帖数据用文件存储

需求用例

image.png

ER 图

image.png

代码开发

分层结构

⭐ 数据层:数据 Model,封装外部数据的塔增删改查,我们的数据存储在本地文件,通过文件操作拉取话题,帖子数据;数据层面向逻辑层,对sevice层是透明,屏蔽下游数据差异,也就是不管下游是文件,还是数据库,还是微服务等,对service层的接口模型是不变的。

⭐ 逻辑层:业务 Entity,处理核心业务逻辑,计算打包业务实体entiy,对应我们的需求,就是话题页面,包括话题和回帖列表,并上送给视图层。

⭐ 视图层:视图 viwe,处理和外部的交互逻辑,以view视图的形式返回给客户端,对于我们需求,我们封装json格式化的请求结果,api形式访问就好。

image.png

组件工具

Gin 高性能 go web 框架github.com/gin-gonic/g…

Go Mod

  • go mod init 初始化依赖管理文件
  • go get gopkg.in/gin-gonic/gin.v1@v1.3.0

Repository

定义结构体

type Topic struct {
    Id         int64  `json:"id"`
    Title      string `json:"title"`
    Content    string `json:"content"`
    CreateTime int64  `json:"create_time"`
}

type Post struct {
    Id         int64  `json:"id"`
    ParentId   int64  `json:"parent_id"`
    Content    string `json:"content"`
    CreateTime int64  `json:"create_time"`
}
index

通过索引快速查找定位我们需要的结果,这里我们用 map 实现内存索引,在服务对外暴露前,利用文件元数据初始化全局内存索引,这样就可以实现O(1)O(1)的时间复杂度查找操作。

var (
    topicIndexMap map[int64]*Topic
    postIndexMap  map[int64][]*Post
)

func initTopicIndexMap(filePath string) error {
    open, err := os.Open(filePath + "topic") // 打开文件
    if err != nil {
            return err
    }
    scanner := bufio.NewScanner(open) // 基于 file 初始化 scanner
    topicTmpMap := make(map[int64]*Topic)
    // 通过迭代器方式遍历数据行,转化为结构体存储至内存 map
    for scanner.Scan() {
            text := scanner.Text()
            var topic Topic
            if err := json.Unmarshal([]byte(text), &topic); err != nil {
                    return err
            }
            topicTmpMap[topic.Id] = &topic
    }
    topicIndexMap = topicTmpMap
    return nil
}
查询
// 根据话题 id 查询话题
type TopicDao struct {
}
var (
    topicDao  *TopicDao
    topicOnce sync.Once
)
func NewTopicDaoInstance() *TopicDao {
    topicOnce.Do(
            func() {
                    topicDao = &TopicDao{}
            })
    return topicDao
}
func (*TopicDao) QueryTopicById(id int64) *Topic {
    return topicIndexMap[id]
}

// 根据话题 id 查询帖子列表
type PostDao struct {
}
var (
    postDao *PostDao
    postOnce sync.Once
)
func NewPostDaoInstance() *PostDao {
    postOnce.Do(
            func() {
                    postDao = &PostDao{}
            })
    return postDao
}
func (*PostDao) QueryPostsByParentId(parentId int64) []*Post {
    return postIndexMap[parentId]
}

Service

实体

// 页面信息
type PageInfo struct {
    Topic    *repository.Topic
    PostList []*repository.Post
}

流程 image.png

func (f *QueryPageInfoFlow) Do() (*PageInfo, error) {
    if err := f.checkParam(); err != nil {
            return nil, err
    }
    if err := f.prepareInfo(); err != nil {
            return nil, err
    }
    if err := f.packPageInfo(); err != nil {
            return nil, err
    }
    return f.pageInfo, nil
}

func (f *QueryPageInfoFlow) checkParam() error {
    if f.topicId <= 0 {
            return errors.New("topic id must be larger than 0")
    }
    return nil
}

/*
话题和回帖信息的获取都依赖topicid,这样这就可以并行执行,提高执行效率。
在做项目开发中,一定要思考流程是否可以并行执行,通过压榨CPU,降低接口耗时。
不要一味的串行实现,浪费多核cpu的资源。
*/
func (f *QueryPageInfoFlow) prepareInfo() error {
    //获取topic信息
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
            defer wg.Done()
            topic := repository.NewTopicDaoInstance().QueryTopicById(f.topicId)
            f.topic = topic
    }()
    //获取post列表
    go func() {
            defer wg.Done()
            posts := repository.NewPostDaoInstance().QueryPostsByParentId(f.topicId)
            f.posts = posts
    }()
    wg.Wait()
    return nil
}

func (f *QueryPageInfoFlow) packPageInfo() error {
    f.pageInfo = &PageInfo{
            Topic:    f.topic,
            PostList: f.posts,
    }
    return nil
}

Controller

构件 View 对象

业务错误码

type PageData struct {
    Code int64       `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
}
func QueryPageInfo(topicIdStr string) *PageData {
    topicId, err := strconv.ParseInt(topicIdStr, 10, 64)
    if err != nil {
        return &PageData{
            Code: -1,
            Msg:  err.Error(),
        }
    }
    pageInfo, err := service.QueryPageInfo(topicId)
    if err != nil {
        return &PageData{
            Code: -1,
            Msg:  err.Error(),
        }
    }
    return &PageData{
        Code: 0,
        Msg:  "success",
        Data: pageInfo,
    }
}

测试运行

Router

初始化数据索引

初始化引擎配置

构建路由

启动服务

func main() {
    if err := Init("./data/"); err != nil {
        os.Exit(-1)
    }
    r := gin.Default()
    r.GET("/community/page/get/:id", func(c *gin.Context) {
        topicId := c.Param("id")
        data := cotroller.QueryPageInfo(topicId)
        c.JSON(200, data)
    })
    err := r.Run()
    if err != nil {
        return
    }
}
func Init(filePath string) error {
    if err := repository.Init(filePath); err != nil {
            return err
    }
    return nil
}

运行

⭐ 通过 go run 进行测试

五、源代码

课程内容相关代码链接GitHub - Moonlight-Zhao/go-project-example at V0