在Web开发中,高并发请求处理是绕不开的话题,Golang凭借原生的goroutine和channel机制,为Web并发开发提供了轻量高效的解决方案,不需要依赖第三方库就能实现复杂的并发逻辑。

Golang Web并发的核心基础
Golang的并发能力主要依托两个核心概念:goroutine和channel。goroutine是Go运行时管理的轻量级线程,创建成本极低,单个程序可以轻松运行成千上万个goroutine;channel则是goroutine之间通信的安全通道,避免了共享内存带来的并发安全问题。
在Web场景中,每个HTTP请求默认会在一个goroutine中处理,我们不需要额外操作就能获得基础的并发处理能力,但如果需要在单个请求中同时处理多个任务,就需要主动使用goroutine来提升效率。
基础goroutine使用
启动一个goroutine只需要在函数调用前加上go关键字,下面是一个简单的示例:
package main
import (
"fmt"
"time"
)
func task(name string) {
for i := 0; i < 3; i++ {
fmt.Printf("任务%s执行第%d次n", name, i)
time.Sleep(time.Second)
}
}
func main() {
// 启动两个并发任务
go task("A")
go task("B")
// 主goroutine等待,避免程序直接退出
time.Sleep(4 * time.Second)
}
Web场景中的并发实战案例
假设我们需要开发一个商品详情接口,接口需要同时获取商品基础信息、商品库存、商品评价三个部分的数据,三个数据源的请求相互独立,使用并发处理可以大幅缩短接口响应时间。
不使用并发的串行实现
先看一下串行处理的实现方式,这种方式会依次请求三个数据源,总耗时是三个请求耗时的总和:
package main
import (
"fmt"
"net/http"
"time"
)
// 模拟获取商品基础信息,耗时1秒
func getProductBase(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d基础信息", id)
}
// 模拟获取商品库存,耗时1秒
func getProductStock(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d库存充足", id)
}
// 模拟获取商品评价,耗时1秒
func getProductComment(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d评价4.8分", id)
}
func productHandler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
id := 1
base := getProductBase(id)
stock := getProductStock(id)
comment := getProductComment(id)
result := fmt.Sprintf("%s,%s,%s", base, stock, comment)
fmt.Fprintf(w, "结果:%s,总耗时:%v", result, time.Since(start))
}
func main() {
http.HandleFunc("/product", productHandler)
http.ListenAndServe(":8080", nil)
}
这个接口的总耗时大概是3秒,用户体验会比较差。
使用并发优化后的实现
使用goroutine并发请求三个数据源,总耗时只需要最长单个请求的耗时,也就是1秒左右:
package main
import (
"fmt"
"net/http"
"time"
"sync"
)
// 模拟获取商品基础信息,耗时1秒
func getProductBase(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d基础信息", id)
}
// 模拟获取商品库存,耗时1秒
func getProductStock(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d库存充足", id)
}
// 模拟获取商品评价,耗时1秒
func getProductComment(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d评价4.8分", id)
}
func productHandler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
id := 1
var (
base string
stock string
comment string
wg sync.WaitGroup
)
// 设置等待三个goroutine完成
wg.Add(3)
// 并发获取基础信息
go func() {
defer wg.Done()
base = getProductBase(id)
}()
// 并发获取库存
go func() {
defer wg.Done()
stock = getProductStock(id)
}()
// 并发获取评价
go func() {
defer wg.Done()
comment = getProductComment(id)
}()
// 等待所有goroutine完成
wg.Wait()
result := fmt.Sprintf("%s,%s,%s", base, stock, comment)
fmt.Fprintf(w, "结果:%s,总耗时:%v", result, time.Since(start))
}
func main() {
http.HandleFunc("/product", productHandler)
http.ListenAndServe(":8080", nil)
}
这里使用了sync.WaitGroup来等待所有并发任务完成,避免使用固定的等待时间,更加可靠。
Web并发开发的注意事项
- 不要在goroutine中直接操作HTTP请求的上下文或者响应体,因为请求处理完成后这些对象可能已经被回收,会导致异常。
- 如果并发任务需要返回结果,除了使用WaitGroup配合外部变量,也可以使用channel来传递结果,避免变量共享带来的竞态问题。
- 不要无限制地创建goroutine,高并发场景下如果请求量过大,大量goroutine会占用过多内存,可以配合协程池控制并发数量。
- 使用goroutine处理耗时任务时,如果任务可能失败,需要做好异常捕获,避免单个goroutine的panic导致整个程序崩溃。
使用channel优化结果传递
上面的例子用外部变量加WaitGroup的方式传递结果,在复杂场景下可能会有竞态风险,使用channel传递结果更加安全:
package main
import (
"fmt"
"net/http"
"time"
)
// 模拟获取商品基础信息,耗时1秒
func getProductBase(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d基础信息", id)
}
// 模拟获取商品库存,耗时1秒
func getProductStock(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d库存充足", id)
}
// 模拟获取商品评价,耗时1秒
func getProductComment(id int) string {
time.Sleep(time.Second)
return fmt.Sprintf("商品%d评价4.8分", id)
}
func productHandler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
id := 1
// 创建传递结果的channel
baseCh := make(chan string)
stockCh := make(chan string)
commentCh := make(chan string)
// 并发获取基础信息
go func() {
baseCh <- getProductBase(id)
}()
// 并发获取库存
go func() {
stockCh <- getProductStock(id)
}()
// 并发获取评价
go func() {
commentCh <- getProductComment(id)
}()
// 从channel接收结果
base := <-baseCh
stock := <-stockCh
comment := <-commentCh
result := fmt.Sprintf("%s,%s,%s", base, stock, comment)
fmt.Fprintf(w, "结果:%s,总耗时:%v", result, time.Since(start))
}
func main() {
http.HandleFunc("/product", productHandler)
http.ListenAndServe(":8080", nil)
}
这种方式下每个任务的结果通过channel传递,不需要共享外部变量,逻辑更加清晰,也更符合Golang的并发设计理念。