Gin (三) 中间件 并发测试

router.GET("/hello",calcTime,func(c *gin.Context){}) 支持多个函数,每个函数一次调用。这样就可以拦截请求

c.Next() 可以在当前函数不退出的情况下,继续执行下一个中间件,等后续的处理完了,又回到当前中间件

go 复制代码
package main

import "github.com/gin-gonic/gin"
import "fmt"
import "time"
func middleWare(c *gin.Context){
        fmt.Println("将要访问index.html")
}

func calcTime(c *gin.Context){
        time1 := time.Now().UnixNano()

        // 调用后续得代码,
        c.Next()
        newTime := time.Now().UnixNano()

        fmt.Printf("%v 纳秒",newTime - time1)
}

func main(){
        router := gin.Default()
        router.GET("/", middleWare, func(c *gin.Context){
                c.String(200, "Hello world")
        })

        router.GET("/hello",calcTime,func(c *gin.Context){
                c.String(200, "Hello world")
        })

        router.Run()
}

并发测试

wrk -t2 -c20 -d30s https://localhost:8000/hello

  • -t2 并发2个线程
  • -c20 20个并发
  • -d30s 持续时间30秒
go 复制代码
package main

import "github.com/gin-gonic/gin"
import "fmt"
import "time"
func middleWare(c *gin.Context){
        fmt.Println("将要访问index.html")
}

func calcTime(c *gin.Context){
        time1 := time.Now().UnixNano()

        // 调用后续得代码,
        c.Next()
        newTime := time.Now().UnixNano()
        _ = newTime - time1
}

func main(){
        // 关闭所有日志
        gin.SetMode(gin.ReleaseMode)
        router := gin.New()
        router.Use(gin.Recovery())

        router.GET("/", middleWare, func(c *gin.Context){
                c.String(200, "Hello world")
        })

        router.GET("/hello",calcTime,func(c *gin.Context){
                c.String(200, "Hello world")
        })

        router.Run()
}
bash 复制代码
go run main.go &
wrk -t2 -c20 -d30s http://192.168.139.204:8080/hello

Running 30s test @ http://192.168.139.204:8080/hello
  2 threads and 20 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    30.37ms   66.17ms 457.06ms   85.66%
    Req/Sec    99.33k    41.62k  181.85k    71.14%
  5472968 requests in 30.09s, 668.09MB read
Requests/sec: 181858.35
Transfer/sec:     22.20MB
相关推荐
森蓝情丶11 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端
JensCS猿11 小时前
从 Spring Boot 回看 SSM 框架:手动挡与自动挡的驾驶哲学
后端
爱勇宝11 小时前
干了近 8 年,一夜之间被裁:AI 时代,程序员最该害怕的不是 AI
前端·后端·程序员
科米米12 小时前
嵌入式日志模块
后端
血小溅12 小时前
三大 AI 编码框架深度对比:GSD vs OpenSpec vs Superpowers
人工智能·后端
ThanksGive12 小时前
层级时间轮看门狗
后端
GetcharZp13 小时前
告别繁琐命令行!这款容器可视化神器,让 Docker/K8s 管理变得如此简单
后端
铁皮饭盒16 小时前
bun直接tsx,优雅!
javascript·后端
Cosolar17 小时前
藏在 Claude Code 里的极致浪漫:完整 187 条 Spinner Verbs 全收录
后端·程序员·代码规范
Csvn18 小时前
Linux 防火墙管理 — firewalld 实战
后端