Golang請求fasthttp實踐

原計劃學完Golang語言HTTP客戶端實踐之後,就可以繼續瞭,沒想到才疏學淺,在搜資料的時候發現除瞭Golang SDK自帶的net/http,還有一個更牛的HttpClient實現github.com/valyala/fasthttp,據說性能是net/http的10倍,我想可能是有點誇張瞭,後期我會進行測試,以正視聽。

在github.com/valyala/fasthttp用到瞭對象池,為瞭在高性能測試中減少內存的使用,fasthttp使用瞭兩個對象池(我隻看瞭這倆):requestPool sync.Pool和responsePool sync.Pool,當然fasthttp也提供瞭正常的對象創建API,後面我在案例中也會寫到。

基礎API演示

首先分享一下基礎的用法封裝:

PS:這個屬於練習版本,所以沒寫多少註釋。

package ft

import (
 "encoding/json"
 "fmt"
 "funtester/task"
 "github.com/valyala/fasthttp"
)


func FastGet(url string, args map[string]interface{}) ([]byte, error) {
 uri := url + "?" + task.ToValues(args)
 _, resp, err := fasthttp.Get(nil, uri)
 if err != nil {
  fmt.Println("請求失敗:", err.Error())
  return nil, err
 }
 return resp, err
}

func FastPostForm(url string, args map[string]interface{}) ([]byte, error) {

 // 填充表單,類似於net/url
 params := &fasthttp.Args{}
 for s, i2 := range args {
  sprintf := fmt.Sprintf("%v", i2)
  params.Add(s, sprintf)
 }
 _, resp, err := fasthttp.Post(nil, url, params)
 if err != nil {
  fmt.Println("請求失敗:", err.Error())
  return nil, err
 }
 return resp, nil
}

func FastPostJson(url string, args map[string]interface{}) ([]byte, error) {

 req := &fasthttp.Request{}
 req.SetRequestURI(url)

 marshal, _ := json.Marshal(args)
 req.SetBody(marshal)

 // 默認是application/x-www-form-urlencoded,其實無所謂
 req.Header.SetContentType("application/json")
 req.Header.SetMethod("POST")

 resp := &fasthttp.Response{}
 if err := fasthttp.Do(req, resp); err != nil {
  fmt.Println("請求失敗:", err.Error())
  return nil, err
 }
 return resp.Body(), nil
}

其中兩點主要註意:

  • FastGet、FastPostForm使用的fasthttp提供的默認獲取請求的方式,FastPostJson使用瞭自定義請求和獲取響應的方式
  • 關於請求頭中的req.Header.SetContentType方法,其實無所謂,服務端都可以解析

高性能API演示

下面分享使用更高的性能(基於對象池)的API創建請求和獲取響應的方式:

package task

import (
 "crypto/tls"
 "encoding/json"
 "fmt"
 "github.com/valyala/fasthttp"
 "log"
 "time"
)

var FastClient fasthttp.Client = fastClient()

// FastGet 獲取GET請求對象,沒有進行資源回收
// @Description:
// @param url
// @param args
// @return *fasthttp.Request
func FastGet(url string, args map[string]interface{}) *fasthttp.Request {
 req := fasthttp.AcquireRequest()
 req.Header.SetMethod("GET")
 values := ToValues(args)
 req.SetRequestURI(url + "?" + values)
 return req
}

// FastPostJson POST請求JSON參數,沒有進行資源回收
// @Description:
// @param url
// @param args
// @return *fasthttp.Request
func FastPostJson(url string, args map[string]interface{}) *fasthttp.Request {
 req := fasthttp.AcquireRequest()
 // 默認是application/x-www-form-urlencoded
 req.Header.SetContentType("application/json")
 req.Header.SetMethod("POST")
 req.SetRequestURI(url)
 marshal, _ := json.Marshal(args)
 req.SetBody(marshal)
 return req
}

// FastPostForm POST請求表單傳參,沒有進行資源回收
// @Description:
// @param url
// @param args
// @return *fasthttp.Request
func FastPostForm(url string, args map[string]interface{}) *fasthttp.Request {
 req := fasthttp.AcquireRequest()
 // 默認是application/x-www-form-urlencoded
 //req.Header.SetContentType("application/json")
 req.Header.SetMethod("POST")
 req.SetRequestURI(url)
 marshal, _ := json.Marshal(args)
 req.BodyWriter().Write([]byte(ToValues(args)))
 req.BodyWriter().Write(marshal)
 return req
}

// FastResponse 獲取響應,保證資源回收
// @Description:
// @param request
// @return []byte
// @return error
func FastResponse(request *fasthttp.Request) ([]byte, error) {
 response := fasthttp.AcquireResponse()
 defer fasthttp.ReleaseResponse(response)
 defer fasthttp.ReleaseRequest(request)
 if err := FastClient.Do(request, response); err != nil {
  log.Println("響應出錯瞭")
  return nil, err
 }
 return response.Body(), nil
}

// DoGet 發送GET請求,獲取響應
// @Description:
// @param url
// @param args
// @return []byte
// @return error
func DoGet(url string, args map[string]interface{}) ([]byte, error) {
 req := fasthttp.AcquireRequest()
 defer fasthttp.ReleaseRequest(req) // 用完需要釋放資源
 req.Header.SetMethod("GET")
 values := ToValues(args)
 req.SetRequestURI(url + "?" + values)
 resp := fasthttp.AcquireResponse()
 defer fasthttp.ReleaseResponse(resp) // 用完需要釋放資源
 if err := FastClient.Do(req, resp); err != nil {
  fmt.Println("請求失敗:", err.Error())
  return nil, err
 }
 return resp.Body(), nil
}

// fastClient 獲取fast客戶端
// @Description:
// @return fasthttp.Client
func fastClient() fasthttp.Client {
 return fasthttp.Client{
  Name:                     "FunTester",
  NoDefaultUserAgentHeader: true,
  TLSConfig:                &tls.Config{InsecureSkipVerify: true},
  MaxConnsPerHost:          2000,
  MaxIdleConnDuration:      5 * time.Second,
  MaxConnDuration:          5 * time.Second,
  ReadTimeout:              5 * time.Second,
  WriteTimeout:             5 * time.Second,
  MaxConnWaitTimeout:       5 * time.Second,
 }
}

測試服務

用的還是moco_FunTester測試框架,腳本如下:

package com.mocofun.moco.main

import com.funtester.utils.ArgsUtil
import com.mocofun.moco.MocoServer
import org.apache.tools.ant.taskdefs.condition.And

class Share extends MocoServer {

    static void main(String[] args) {
        def util = new ArgsUtil(args)
        //                def server = getServerNoLog(util.getIntOrdefault(0,12345))
        def server = getServer(util.getIntOrdefault(0, 12345))
        server.get(both(urlStartsWith("/test"),existArgs("code"))).response("get請求")
        server.post(both(urlStartsWith("/test"), existForm("fun"))).response("post請求form表單")
        server.post(both(urlStartsWith("/test"), existParams("fun"))).response("post請求json表單")
        server.get(urlStartsWith("/qps")).response(qps(textRes("恭喜到達QPS!"), 1))
//        server.response(delay(jsonRes(getJson("Have=Fun ~ Tester !")), 1000))
        server.response("Have Fun ~ Tester !")
        def run = run(server)
        waitForKey("fan")
        run.stop()
    }
}

Golang單元測試

第一次寫Golang單測,有點不適應,搞瞭很久才通。

package test

import (
 "funtester/ft"
 "funtester/task"
 "log"
 "testing"
)

const url = "http://localhost:12345/test"

func args() map[string]interface{} {
 return map[string]interface{}{
  "code": 32,
  "fun":  32,
  "msg":  "324",
 }
}

func TestGet(t *testing.T) {
 get := task.FastGet(url, args())
 res, err := task.FastResponse(get)
 if err != nil {
  t.Fail()
 }
 v := string(res)
 log.Println(v)
 if v != "get請求" {
  t.Fail()
 }
}

func TestPostJson(t *testing.T) {
 post := task.FastPostJson(url, args())
 res, err := task.FastResponse(post)
 if err != nil {
  t.Fail()
 }
 v := string(res)
 log.Println(v)
 if v != "post請求json表單" {
  t.Fail()
 }
}

func TestPostForm(t *testing.T) {
 post := task.FastPostForm(url, args())
 res, err := task.FastResponse(post)
 if err != nil {
  t.Fail()
 }
 v := string(res)
 log.Println(v)
 if v != "post請求form表單" {
  t.Fail()
 }
}

func TestGetNor(t *testing.T) {
 res, err := ft.FastGet(url, args())
 if err != nil {
  t.Fail()
 }
 v := string(res)
 log.Println(v)
 if v != "get請求" {
  t.Fail()
 }
}

func TestPostJsonNor(t *testing.T) {
 res, err := ft.FastPostJson(url, args())
 if err != nil {
  t.Fail()
 }
 v := string(res)
 log.Println(v)
 if v != "post請求json表單" {
  t.Fail()
 }
}

func TestPostFormNor(t *testing.T) {
 res, err := ft.FastPostForm(url, args())
 if err != nil {
  t.Fail()
 }
 v := string(res)
 log.Println(v)
 if v != "post請求form表單" {
  t.Fail()
 }
}

測試報告

用的自帶的控制臺輸出內容:

=== RUN   TestGet
2021/10/18 18:56:49 get請求
— PASS: TestGet (0.01s)
=== RUN   TestPostJson
2021/10/18 18:56:49 post請求json表單
— PASS: TestPostJson (0.00s)
=== RUN   TestPostForm
2021/10/18 18:56:49 post請求form表單
— PASS: TestPostForm (0.00s)
=== RUN   TestGetNor
2021/10/18 18:56:49 get請求
— PASS: TestGetNor (0.00s)
=== RUN   TestPostJsonNor
2021/10/18 18:56:49 post請求json表單
— PASS: TestPostJsonNor (0.00s)
=== RUN   TestPostFormNor
2021/10/18 18:56:49 post請求form表單
— PASS: TestPostFormNor (0.00s)
=== RUN   TestStageJSON

到此這篇關於Golang請求fasthttp實踐的文章就介紹到這瞭,更多相關Golang請求fasthttp內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: