1. 程式人生 > 其它 >go gin 計算請求qps

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 +" \n")
	//}
	//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/[email protected]
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/