当前位置: 首页 > 工具软件 > fasthttp > 使用案例 >

golang 高并发的http请求fasthttp

陶鹏
2023-12-01

以前写接口测试的代码,用go自带的http库,当需要高并发的时候,报连接数不够的错误,无法满足要求,查阅相关资料,三方库fasthttp可以很好的支持高并发,区别在于fasthttp使用了连接池,达到了很好的连接复用的效果

源码:

fasthttp.AcquireResponse()

> AcquireResponse returns an empty Response instance from response pool.
> 
> The returned Response instance may be passed to ReleaseResponse when
> it is no longer needed. This allows Response recycling, reduces GC
> pressure and usually improves performance.

主要方法:

fasthttp.AcquireRequest()//获取Request连接池中的连接
fasthttp.ReleaseRequest(req) // 用完需要释放资源
fasthttp.AcquireResponse()//获取Response连接池中的连接
fasthttp.ReleaseResponse(resp) // 用完需要释放资源
fasthttp.Do(req, resp)

这样代码也非常简洁,逻辑非常清晰

直接上代码:

package request

import (
	"github.com/valyala/fasthttp"
	log "github.com/wonderivan/logger"
    // "time"
    // "github.com/tidwall/gjson"

)
var getcount int =1
var postcount int =1
/**
 * @description: test
 * @Author: WangZhouFeng
 * @param : 
 * @return: 
 * @Date: 2020-01-13 14:12:27
 */
func Post(url string){
    req := fasthttp.AcquireRequest()//获取Request连接池中的连接
    defer fasthttp.ReleaseRequest(req) // 用完需要释放资源    
    // 默认是application/x-www-form-urlencoded
    req.Header.SetContentType("application/json")
    req.Header.SetMethod("POST")    
    req.SetRequestURI(url)    
    // requestBody := []byte(`{"request":"test"}`)
    // req.SetBody(requestBody)
    resp := fasthttp.AcquireResponse()//获取Response连接池中的连接
    defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源
    if err := fasthttp.Do(req, resp); err != nil {//发送请求
		log.Error(err)
        return
    }
	b := resp.Body()
    // resp.Body()
    log.Info(b)
}
/**
 * @description: test
 * @Author: WangZhouFeng
 * @param : 
 * @return: 
 * @Date: 2020-01-13 14:12:21
 */
 //带HERDER和QUERY的get请求
func Get(url string,header map[string]string,query map[string]string) ([]byte,error) {
    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
    
    // 默认是application/x-www-form-urlencoded
    // req.Header.SetContentType("application/json")
    req.Header.SetContentType("application/x-www-form-urlencoded")

    req.Header.SetMethod("GET")
    //set header
    for k, v := range header {
		req.Header.Set(k, v)
    }
    //set query
    if len(query) !=0{
        url = url + "?"
        url1 := ""
        for k,v := range query{
            temp := k+"="+v
            url1 = url1+"&"+temp
        }
        url1 = url1[1:len(url1)]
        url = url + url1
    }
    req.SetRequestURI(url)

    // log.Info(&req.Header)//获取header
    // log.Info(string(req.RequestURI()))//获取url
    // log.Info(string(req.Body()))//获取body

    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源

    if err := fasthttp.Do(req, resp); err != nil {
        log.Error(err)
        return nil,err
     
    }
    // for k,v :=range(query){
    //     log.Info(k+":"+v)
    // }
    body := string(resp.Body())
    // log.Info(body)
    log.Info(getcount)
    getcount++
	return []byte(body),nil
}
// 带header,form,query的post请求通用
func Postdata(header map[string]string,form map[string]string,data map[string]string,url string) (err error,body []byte) {
    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
    // 默认是application/x-www-form-urlencoded
    req.Header.SetContentType("application/x-www-form-urlencoded")
    req.Header.SetMethod("POST")
    req.Header.Set("Accept-language","zh-cn")

    // 拼接query
    if len(data) !=0{
        url = url + "?"
        url1 := ""
        for k,v := range data{
            temp := k+"="+v
            url1 = url1+"&"+temp
        }
        url1 = url1[1:len(url1)]
        url = url + url1
    }
    req.SetRequestURI(url)

    //添加header
	for k, v := range header {
		req.Header.Set(k, v)
    }
    //添加form
    if len(form) !=0{
        param :=""
        for k, v := range form {
            temp := k+"="+v
            param = param +"&"+temp
        }
        param = param[1:len(param)]
        req.SetBodyString(param)
    }
    // log.Info(&req.Header)//获取header
    // log.Info(string(req.RequestURI()))//获取url
    // log.Info(string(req.Body()))//获取body
    // log.Info(string(req.R()))//获取url

    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源

    if err := fasthttp.Do(req, resp); err != nil {
        log.Error(err)
        return err,nil
    }
    body = resp.Body()
    // log.Info(string(body))

    // if resp.StatusCode() != fasthttp.StatusOK {
    //     log.Error("ACTIVITY unexpected status code: %d\n", resp.StatusCode())
    //     return
    // }else{
    //     json := body
    //     //format需要的值,处理code,写 log
    //     code := gjson.Get(json, "code").Int()
    //     if code == 10000{
    //         log.Info(body)
    //         return 
    //     }else{

    //         return
    //     }
    // }
    log.Info(postcount)
    postcount++
    fasthttp.ReleaseRequest(req)
    fasthttp.ReleaseResponse(resp)
    return err,[]byte(body)
}


func Deletedata(header map[string]string,form map[string]string,data map[string]string,url string) (err error,body []byte) {
    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
    // 默认是application/x-www-form-urlencoded
    req.Header.SetContentType("application/x-www-form-urlencoded")
    req.Header.SetMethod("DELETE")
    req.Header.Set("Accept-language","zh-cn")

    // 拼接query
    if len(data) !=0{
        url = url + "?"
        url1 := ""
        for k,v := range data{
            temp := k+"="+v
            url1 = url1+"&"+temp
        }
        url1 = url1[1:len(url1)]
        url = url + url1
    }
    req.SetRequestURI(url)

    //添加header
	for k, v := range header {
		req.Header.Set(k, v)
    }
    //添加form
    if len(form) !=0{
        param :=""
        for k, v := range form {
            temp := k+"="+v
            param = param +"&"+temp
        }
        param = param[1:len(param)]
        req.SetBodyString(param)
    }
    // log.Info(&req.Header)//获取header
    log.Info(string(req.RequestURI()))//获取url
    // log.Info(string(req.Body()))//获取body

    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源

    if err := fasthttp.Do(req, resp); err != nil {
        log.Error(err)
        return err,nil
    }
    body = resp.Body()
    log.Info(string(body))

    // if resp.StatusCode() != fasthttp.StatusOK {
    //     log.Error("ACTIVITY unexpected status code: %d\n", resp.StatusCode())
    //     return
    // }else{
    //     json := body
    //     //format需要的值,处理code,写 log
    //     code := gjson.Get(json, "code").Int()
    //     if code == 10000{
    //         log.Info(body)
    //         return 
    //     }else{

    //         return
    //     }
    // }
    fasthttp.ReleaseRequest(req)
    fasthttp.ReleaseResponse(resp)
    return err,[]byte(body)
}




func Putdata(header map[string]string,form map[string]string,data map[string]string,url string) (err error,body []byte) {
    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
    // 默认是application/x-www-form-urlencoded
    req.Header.SetContentType("application/x-www-form-urlencoded")
    req.Header.SetMethod("PUT")
    req.Header.Set("Accept-language","zh-cn")

    // 拼接query
    if len(data) !=0{
        url = url + "?"
        url1 := ""
        for k,v := range data{
            temp := k+"="+v
            url1 = url1+"&"+temp
        }
        url1 = url1[1:len(url1)]
        url = url + url1
    }
    req.SetRequestURI(url)

    //添加header
	for k, v := range header {
		req.Header.Set(k, v)
    }
    //添加form
    if len(form) !=0{
        param :=""
        for k, v := range form {
            temp := k+"="+v
            param = param +"&"+temp
        }
        param = param[1:len(param)]
        req.SetBodyString(param)
    }
    // log.Info(&req.Header)//获取header
    log.Info(string(req.RequestURI()))//获取url
    // log.Info(string(req.Body()))//获取body

    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源

    if err := fasthttp.Do(req, resp); err != nil {
        log.Error(err)
        return err,nil
    }
    body = resp.Body()
    log.Info(string(body))

    // if resp.StatusCode() != fasthttp.StatusOK {
    //     log.Error("ACTIVITY unexpected status code: %d\n", resp.StatusCode())
    //     return
    // }else{
    //     json := body
    //     //format需要的值,处理code,写 log
    //     code := gjson.Get(json, "code").Int()
    //     if code == 10000{
    //         log.Info(body)
    //         return 
    //     }else{

    //         return
    //     }
    // }
    fasthttp.ReleaseRequest(req)
    fasthttp.ReleaseResponse(resp)
    return err,[]byte(body)
}

 类似资料: