一 request
gin框架的每一个request请求都会开一个goroutine来处理,所以天然支持高并发
二 handle
func main() {
r := gin.Default()
r.GET("/long_async", func(c *gin.Context) {
// 创建要在goroutine中使用的副本
cCp := c.Copy()
go func() {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// 这里使用你创建的副本
log.Println("Done! in path " + cCp.Request.URL.Path)
}()
})
r.GET("/long_sync", func(c *gin.Context) {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// 这里没有使用goroutine,所以不用使用副本
log.Println("Done! in path " + c.Request.URL.Path)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
浏览器分别访问http://localhost:8080/long_sync http://localhost:8080/long_async 会发现async会立马抛出返回,而sync则是同步等待到任务结束
三 sync.WaitGroup
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"sync"
"time"
)
func main() {
r := gin.Default()
a := 1
r.GET("/long_async", func(c *gin.Context) {
var wg sync.WaitGroup
// 创建要在goroutine中使用的副本
cCp := c.Copy()
wg.Add(1)
go func() {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// 这里使用你创建的副本
log.Println("Done! in path " + cCp.Request.URL.Path)
wg.Done()
}()
wg.Add(1)
go func() {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// 这里使用你创建的副本
log.Println("Done2! in path " + cCp.Request.URL.Path)
wg.Done()
}()
wg.Add(1)
go func() {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(2 * time.Second)
log.Println("a1", a )
a = 2
log.Println("a11", a )
// 这里使用你创建的副本
log.Println("Done3! in path " )
wg.Done()
}()
wg.Add(1)
go func() {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
log.Println("a2", a )
// 这里使用你创建的副本
log.Println("Done2! in path " + c.Request.URL.Path)
wg.Done()
}()
wg.Wait()
fmt.Println("request done")
})
r.GET("/long_sync", func(c *gin.Context) {
// simulate a long task with time.Sleep(). 5 seconds
time.Sleep(5 * time.Second)
// 这里没有使用goroutine,所以不用使用副本
log.Println("Done! in path " + c.Request.URL.Path)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}