gin的timeout middleware实现(续2)

版权声明 本站原创文章 由 萌叔 发表 转载请注明 萌叔 | http://vearne.cc 1. 前言 笔者连续2篇文章,探讨如何开发一个gin的timeout middleware,但是"百密一疏"啊。仍然考虑的不够周全。 笔者的文章 gin的timeout middleware实现(续) 中实现的程序有2个问题 func Timeout(t time.Duration) gin.HandlerFunc { return func(c *gin.Context) { // sync.Pool buffer := buffpool.GetBuff() blw := &SimplebodyWriter{body: buffer, ResponseWriter: c.Writer} c.Writer = blw // wrap the request context with a timeout ctx, cancel := context.WithTimeout(c.Request.Context(), t) c.Request = c.Request.WithContext(ctx) finish := make(chan struct{}) // 子协程 // ****************注意*************** // 创建的子协程没有recover,存在程序崩溃的风险 go func() { c.Next() finish <- struct{}{} }() // ****************注意*************** select { case <-ctx.Done(): // ****************注意*************** // 子协程和父协程存在同时修改Header的风险 // 由于Header是个map,可能诱发 // fatal error: concurrent map read and map write c.Writer.WriteHeader(http.StatusGatewayTimeout) // ****************注意*************** c.Abort() // 超时发生, 通知子协程退出 cancel() // 如果超时的话,buffer无法主动清除,只能等待GC回收 case <-finish: // 结果只会在主协程中被写入 blw.ResponseWriter.Write(buffer.Bytes()) buffpool.PutBuff(buffer) } } } 2. 解决 main.go ...

June 6, 2019 · 4 min

gin的timeout middleware实现(续)

版权声明 本站原创文章 由 萌叔 发表 转载请注明 萌叔 | http://vearne.cc 1. 前言 在笔者的上一篇文章中,我们探讨了如何开发一个对业务无侵入的timeout middleware的实现,但是遗留了问题。在超时发生时,后台运行的子协程可能会不断累积,造成协程的泄露,最终引发程序奔溃。 2. 解决 为了解决子协程退出的问题,我们需要在超时发生时,通知子协程,让其也尽快退出。 下面的例子中,gin的处理函数long(c *gin.Context)中有对gRPC服务的调用 我们使用grpc/grpc-go 中提供的 greeter_server来提供gRPC服务 // Package main implements a server for Greeter service. package main import ( "context" "log" "net" "time" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" ) const ( port = ":50051" ) // server is used to implement helloworld.GreeterServer. type server struct{} // SayHello implements helloworld.GreeterServer func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { log.Printf("Received: %v", in.Name) time.Sleep(2*time.Second) return &pb.HelloReply{Message: "Hello " + in.Name}, nil } func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } gin相关代码 main.go ...

May 20, 2019 · 3 min

gin的timeout middleware实现

版权声明 本站原创文章 由 萌叔 发表 转载请注明 萌叔 | http://vearne.cc 1. 前言 说到Golang中应用最广泛的web框架,恐怕非gin-gonic/gin莫属了。在服务中,如果它依赖的后端服务出现异常,我们希望错误能够快速的暴露给调用方,而部署无限期的等待。我们需要一个timeout middleware, 来完成这个目标。 对于gin框架,timeout middleware可参考的资料,比较多见的是参考资料1,但是它的实现,对业务代码造成了入侵,不是很友好,这里给出笔者的实现,供大家参考 2. 实现 直接上代码 main.go package main import ( "bytes" "github.com/gin-gonic/gin" "github.com/vearne/golib/buffpool" "log" "net/http" "time" ) type SimplebodyWriter struct { gin.ResponseWriter body *bytes.Buffer } func (w SimplebodyWriter) Write(b []byte) (int, error) { return w.body.Write(b) } func Timeout(t time.Duration) gin.HandlerFunc { return func(c *gin.Context) { // sync.Pool buffer := buffpool.GetBuff() blw := &SimplebodyWriter{body: buffer, ResponseWriter: c.Writer} c.Writer = blw finish := make(chan struct{}) go func() { // 子协程只会将返回数据写入到内存buff中 c.Next() finish <- struct{}{} }() select { case <-time.After(t): c.Writer.WriteHeader(http.StatusGatewayTimeout) c.Abort() // 1. 主协程超时退出。此时,子协程可能仍在运行 // 如果超时的话,buffer无法主动清除,只能等待GC回收 case <-finish: // 2. 返回结果只会在主协程中被写入 blw.ResponseWriter.Write(buffer.Bytes()) buffpool.PutBuff(buffer) } } } func short(c *gin.Context) { time.Sleep(1 * time.Second) c.JSON(http.StatusOK, gin.H{"hello":"world"}) } func long(c *gin.Context) { time.Sleep(5 * time.Second) c.JSON(http.StatusOK, gin.H{"hello":"world"}) } func main() { // create new gin without any middleware engine := gin.New() // add timeout middleware with 2 second duration engine.Use(Timeout(time.Second * 2)) // create a handler that will last 1 seconds engine.GET("/short", short) // create a route that will last 5 seconds engine.GET("/long", long) // run the server log.Fatal(engine.Run(":8080")) } 简单解释一下: ...

May 16, 2019 · 2 min

gin 统计请求状态信息

版权声明 本站原创文章 由 萌叔 发表 转载请注明 萌叔 | http://vearne.cc 1. 引言 gin-gonic/gin 是Golang API 开发中最常用到的web框架。我们可以轻松的写一个gin的中间件获取HTTP的状态码, 然后暴露给phrometheus。但是如果我想获取的body体中的错误码呢? 2. 官方的例子 package main import ( "time" "log" "github.com/gin-gonic/gin" ) func Logger() gin.HandlerFunc { return func(c *gin.Context) { t := time.Now() // Set example variable c.Set("example", "12345") // before request c.Next() // after request latency := time.Since(t) log.Println("latency", latency) // access the status we are sending status := c.Writer.Status() log.Println("status_code", status) } } func main() { r := gin.New() r.Use(Logger()) r.GET("/test", func(c *gin.Context) { example := c.MustGet("example").(string) // it would print: "12345" log.Println(example) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } 3. 读取body中的错误码 假定我们的服务在请求处理失败的情况下,返回如下结构体 ...

October 16, 2018 · 2 min

kingshard初探

版权声明 本站原创文章 由 萌叔 发表 转载请注明 萌叔 | http://vearne.cc 起因:之前的相当长时间一直在寻找mysql的分布式解决方案,一直没有特别理想的答案,有同事给推荐了kingshard,所以决定一探究竟。 1.安装 机器共3台 机器 IP 说明 机器1 192.168.122.1 安装kingshard 机器1 192.168.122.3 安装mysql实例(node1) master 没有slave 机器1 192.168.122.4 安装mysql实例(node2) master 没有slave 安装请参考官方资料 https://github.com/flike/kingshard/blob/master/doc/KingDoc/kingshard_install_document.md 我安装的kingshard 2016年8月9日的版本,目前kingshard还没有参数或配置,把kingshard以后台守护进程的方式启动,因此作者建议使用supervisor进行管理。 因为我主要是为了观察效果,所以直接在终端中启动 ./kingshard -config=../etc/ks.yaml 以下是我的配置文件 ks.yaml # server listen addr addr : 0.0.0.0:9696 # server user and password user : kingshard password : kingshard # if set log_path, the sql log will write into log_path/sql.log,the system log # will write into log_path/sys.log #log_path : /Users/flike/log # log level[debug|info|warn|error],default error log_level : debug # if set log_sql(on|off) off,the sql log will not output log_sql: on # only log the query that take more than slow_log_time ms #slow_log_time : 100 # the path of blacklist sql file # all these sqls in the file will been forbidden by kingshard #blacklist_sql_file: /Users/flike/blacklist # only allow this ip list ip to connect kingshard #allow_ips: 127.0.0.1 # the charset of kingshard, if you don't set this item # the default charset of kingshard is utf8. #proxy_charset: gbk # node is an agenda for real remote mysql server. nodes : - name : node1 # default max conns for mysql server max_conns_limit : 32 # all mysql in a node must have the same user and password user : kingshard password : kingshard # master represents a real mysql master server master : 192.168.122.3:3306 # slave represents a real mysql salve server,and the number after '@' is # read load weight of this slave. #slave : 192.168.59.101:3307@2,192.168.59.101:3307@3 down_after_noalive : 32 - name : node2 # default max conns for mysql server max_conns_limit : 32 # all mysql in a node must have the same user and password user : kingshard password : kingshard # master represents a real mysql master server master : 192.168.122.4:3306 # slave represents a real mysql salve server slave : # down mysql after N seconds noalive # 0 will no down down_after_noalive: 32 # schema defines sharding rules, the db is the sharding table database. schema : db : kingshard nodes: [node1,node2] default: node1 shard: - table: test_shard_day key: mtime # 指定分表所用的时间字段 type: date_day nodes: [node1,node2] date_range: [20160306-20160307,20160308-20160309] 由于我主要是用到kingshard的按时间分表功能,所以这里只配置了 ...

January 1, 2018 · 4 min