这是我参与「第五届青训营 」伴学笔记创作活动的第2天
语言进阶 并发编程
Go可以充分发挥多个核的优势,多线程程序在一个核上分片执行,利用多核可以在同一时间并行执行,提高效率
有比线程更轻量的协程
goroutine
快速打印5次hello
func Hello(i int) {
fmt.Println("hello goroutine : ", i)
}
func HelloGoRoutine() {
for i := 0; i < 5; i++ {
go func(j int) {
Hello(j)
}(i)
}
time.Sleep(time.Second)
}
CSP
C/C++使用管道、共享内存等方式实现进程间通信
Go提倡通过通信来实现共享内存
channel通道
make(chan 元素类型,[缓冲大小])
类似生产者-消费者模型,先有第一个子协程生成0~9,再由另一个子协程读取数字并进行平方操作
func CalSquare() {
src := make(chan int)
dest := make(chan int, 3)
// 生产者
go func() {
defer close(src)
for i := 0; i < 10; i++ {
src <- i
}
}()
// 消费者
go func() {
defer close(dest)
for i := range src {
dest <- i * i
}
}()
for i := range dest {
fmt.Println(i)
}
}
并发安全
如果没有锁,上述代码可能会出现两个协程竞争的情况,同时对一个变量进行操作,稳妥的方法是一个协程拿到资源后就对资源进行加锁,等它操作完成之后再解锁。加锁期间其他协程都无法对该资源进行读写
同C/C++,使用sync.Mutex互斥锁进行加速、解锁操作
func addWithLock() {
for i := 0; i < 2000; i++ {
lock.Lock()
x++
lock.Unlock()
}
}
WaitGroup
正常情况下,新激活的goroutine是不知道什么时候结束的,我们需要直到goroutine什么时候完成,需要借助sync的WaitGroup来实现
-
Add() 每次激活想要被等待完成的goroutine之前,先调用Add(),用来设置或添加要等待完成的goroutine的数量。
Add(5)设置计数器的值为5,需要等待5个goroutine完成
-
Done():每次需要等待的goroutine在完成之前,应该调用Done()方法来表示goroutine完成了,调用后会让计数器值-1
-
Wait():在等待计数器减为0之前,Wait()会阻塞当前协程
有点类似于信号量
func hello(x int) {
fmt.Printf("hello wait group : %v\n", x)
}
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() // 只有当运行了5个goroutine之后才会退出函数
}
依赖管理
目前应用最多:Go Module(类似于java的Maven)
$GOPATH、Go Vender不作记录
- 通过go.mod文件管理依赖包版本(类似maven的pom.xml)
- 通过go mod指令下载等
依赖管理三要素:
- 配置文件、描述依赖: go.mod
- 中心仓库管理依赖库: Proxy
- 本地工具: go get/mod
go.mod文件的格式
module example/project/app:依赖管理基本单元
go xxx 原生库
require(
example/lib v1.0.2
)
常用的go mod指令:
go mod init // 初始化,创建go.mod文件
go mod download // 下载模块到本地缓存
go mod tidy // 增加需要的依赖,删除不需要的依赖
依赖的东西会有版本的区别,这里分语义版本:{MAJOR}.{PATCH}和基于commit提交的伪版本
依赖会选择最低兼容的版本,如下图,最终编译时会采用V1.4版本
go proxy是一个缓存站点,会缓存第三方代码托管平台的一些代码,可以使依赖稳定(应该像maven的本地仓库、中心仓库)
测试
规则:
-
所有测试文件以_test.go结尾
-
函数命名规范:func TestXxx(* testing T)
-
初始化逻辑放到TestMain中
func TestMain(m *testing.M) { // 测试前:数据状态、配置初始化等前置工作 code := m.Run() // 测试所有 // 测试后:释放资源等收尾工作 os.Exit(code) }
代码覆盖率:表示测试用例的覆盖度
实战
社区话题页面:
- 实现一个展示话题(标题,文字描述)和回帖列表的后端http接口;
- 本地文件存储数据
用到的技术点:
- web框架:Gin
- 分层结构设计:MVC架构
- 文件操作
- 数据查询
Repository层:
在db_init.go中建立索引map:
var (
topicIndexMap map[int64]*Topic // 话题
postIndexMap map[int64][]*Post // 回帖
)
repository用到单例模式:
func NewPostDaoInstance() *PostDao {
postOnce.Do(
func() {
postDao = &PostDao{}
})
return postDao
}
// 查询回帖可以直接
repository.NewPostDaoInstance.QueryTopicById(id)
然后在topic.go中编写根据话题id查找话题:
func (*TopicDao) QueryTopicById(id int64) *Topic {
return topicIndexMap[id]
}
service层:
结构体pageInfo表示一个完整帖子
type PageInfo struct {
Topic *repository.Topic
PostList []*repository.Post
}
查询的流程:参数校验->准备数据->组装实体
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
}
其中,准备数据这个操作需要用到repository层给的数据,这里并行执行查询话题和回帖的消息
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() // 等待两个goroutine执行完
return nil
}
Controller层:
定义了一个结构体返回消息
// 根据上面传来的topicID来查询Topic
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,
}
}
main.go:
用到Gin框架,流程:初始化数据索引->初始化引擎配置->构建路由->启动服务
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
}
}
运行程序后,使用curl命令来测试接口:
curl --location --request GET 'http://0.0.0.0:8080/community/page/get/2'
作业:
- 支持对话题发布回帖
- 回帖id生成需要保证不重复、唯一性
- 新加回帖追加到本地文件,同时需要更新索引,注意Map的并发安全问题
首先在repository层,我们根据传进来的post,加入到文件系统并更新索引
// 发布帖子,根据传来的Post实体
func (*PostDao) AddPost(post *Post) error {
f, err := os.OpenFile("./data/post", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
defer f.Close()
appendPost, _ := json.Marshal(post) // 将帖子序列化
if _, err = f.WriteString(string(appendPost) + "\n"); err != nil {
return err
}
rwMutex.Lock()
postList, ok := postIndexMap[post.ParentId]
if !ok { // 如果没有查询到,说明这个话题下没有post,创建一个新的post
postIndexMap[post.ParentId] = []*Post{post}
} else {
// 添加post
postList = append(postList, post)
// 更新索引
postIndexMap[post.ParentId] = postList
}
rwMutex.Unlock()
return nil
}
然后在service层处理业务逻辑:
个人的想法:把post的id做成连续的,然后添加post的时候查询最新的到哪里,然后把这个数 + 1就是新的post的id,更好的方法是采用IdWorker,先全局随机变量:
import (
idworker "github.com/gitstliu/go-id-worker"
)
var idGen *idWorker.IdWorker
然后在需要id的时候:
func Init() {
idGen = &idworker.IdWorker{}
idGen.InitIdWorker(1, 1)
}
id, err := idGen.NextId()
if err != nil {
return err
}
post.Id = id
Post一共有4个字段,除去id有三个字段:topicId、content由上面传,time由系统生成,这三个字段先组成一个结构体PublishPostFlow
type PublishPostFlow struct {
content string
topicId int64
postId int64
}
所以在service层的逻辑是:
上面传来topicId、content,然后生成PublishPostFlow,然后调用PublishPostFlow里的Do方法,这个Do方法分成两步:检查参数、发布回帖
// 检查参数
func (f *PublishPostFlow) checkParam() error {
if len(utf16.Encode([]rune(f.content))) >= 500 {
return errors.New("content length must be less than 500")
}
// 发布回帖
func (f *PublishPostFlow) publish() error {
post := &repository.Post{
ParentId: f.topicId,
Content: f.content,
CreateTime: time.Now().Unix(),
}
id, err := idGen.NextId()
if err != nil {
return err
}
post.Id = id
if err := repository.NewPostDaoInstance().AddPost(post); err != nil {
return err
}
f.postId = post.Id
return nil
}
Controller层的逻辑就是将上层传来的string类型的topicId转化成int64,然后调用service层的方法得到PostId,然后返回给上层
func PublishPost(topicIdStr string, content string) *PageData {
topicId, _ := strconv.ParseInt(topicIdStr, 10, 64)
postId, err := service.PublishPost(topicId, content)
if err != nil {
return &PageData{
Code: -1,
Msg: err.Error(),
}
}
return &PageData{
Code: 0,
Msg: "success",
Data: map[string]int64{
"post_id": postId,
},
}
}
main函数里的更新:
r.POST("/community/post/do", func(c *gin.Context) {
topicId, _ := c.GetPostForm("topic_id")
content, _ := c.GetPostForm("content")
data := controller.PublishPost(topicId, content)
c.JSON(200, data)
})