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
相关推荐
fliter1 小时前
你想在 Rust 中实现动态库热重载?
后端
用户467245132231 小时前
分布式唯一序列号:万亿级订单不重复的奥秘
后端
未秃头的程序猿1 小时前
别再让大模型单打独斗了!Java 多 Agent 协作实战:任务拆解+结果聚合
java·后端·ai编程
XovH1 小时前
第29篇 k8s之Service 与 Endpoints 深入:服务发现原理
后端
人道领域1 小时前
【LeetCode刷题日记】538.把二叉搜索树转换为累加树
java·开发语言·后端·算法·leetcode
西凉的悲伤1 小时前
Spring Boot + ShardingSphere 介绍
java·spring boot·后端·shardingsphere·分库分表
不爱编程的小陈1 小时前
Go内存模型与GC机制:高性能编程的核心
开发语言·后端·golang
日月云棠1 小时前
12 Enum —— 枚举类型的底层实现
java·后端
工位植物人1 小时前
深入理解Java中的类、抽象类、接口与枚举类
后端