go gin 计算请求qps

想计算flink udf发起请求的qps,写了个简单的gin

package main

import (
	"bufio"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"strconv"
	"time"
)

var QpsCount = 0
var START_TIME = time.Now().Unix()
var TimeList = make(map[int64]int)

func checkFileIsExist(filename string) bool {
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return false
	}
	return true
}
func logContent(str string, filename string) {
	filePath := filename
	file, openErr := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, 0666)
	if openErr != nil {
		fmt.Println("文件打开失败", openErr)
		createFile, createErr := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
		if createErr != nil {
			fmt.Println("文件创建失败", openErr)
		} else {
			file = createFile
		}
	}
	//及时关闭file句柄
	defer file.Close()
	//写入文件时,使用带缓存的 *Writer
	write := bufio.NewWriter(file)
	//for i := 0; i < 5; i++ {
	write.WriteString(str +" 
")
	//}
	//Flush将缓存的文件真正写入到文件中
	write.Flush()
}

func indexFunc(c *gin.Context) {
	// 首页
	QpsCount += 1
	var timeInterval int64 = 1
	currentTime := time.Now().Unix()
	if currentTime % timeInterval==0 {
		if _, ok := TimeList[currentTime]; !ok {
			TimeList[currentTime] = QpsCount
			addCount := QpsCount - TimeList[currentTime-timeInterval]
			logContent(strconv.FormatInt(currentTime, 10) +
				"   运行时间:"  + strconv.FormatInt(currentTime-START_TIME, 10) +
				"  请求总数" + strconv.Itoa(QpsCount) +
				"   请求增量" + strconv.Itoa(addCount), "count_log")
		}
	}
	c.String(http.StatusOK, "ok")
}


func main() {
	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()
	router.GET("", indexFunc)
	router.Run("0.0.0.0:8023")
}

跨平台生成linux可执行文件

export GO111MODULE=off
export CGO_ENABLED=0
export GOOS=linux
export GOARCH=amd64
go build main.go

mac 安装go & gin

brew install go
go env|grep GOPATH

vi ~/.bash_profile
export GOPATH=/Users/huim/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOBIN

# 七牛云镜像
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct

go get -u github.com/gin-gonic/gin
# 包管理工具
go get github.com/kardianos/govendor

# 创建文件夹并进入项目文件夹
govendor init
export https_proxy=http://127.0.0.1:7890 http_proxy=http://127.0.0.1:7890 all_proxy=socks5://127.0.0.1:7890
govendor fetch github.com/gin-gonic/gin@v1.3
curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go

# 安装依赖包
govendor fetch github.com/golang/protobuf/proto
govendor fetch github.com/ugorji/go/codec
govendor fetch gopkg.in/go-playground/validator.v8
govendor fetch gopkg.in/yaml.v2
govendor fetch github.com/gin-contrib/sessions
govendor fetch github.com/gin-contrib/sessions/cookie

# redis - session
govendor get github.com/gin-contrib/sse
govendor get github.com/gin-gonic/gin/binding

# https://linuxize.com/post/how-to-install-go-on-centos-7/
原文地址:https://www.cnblogs.com/huim/p/15161142.html