美文网首页
简单对比openresty和go的性能

简单对比openresty和go的性能

作者: 小肥爬爬 | 来源:发表于2023-09-08 11:59 被阅读0次

    思路

    • 用openresty/go 各写http服务
    • 用30w数据, 经jmeter 发送测试. jmeter 线程参数: 1000/50/300

    openresty

    nginx配置

    worker_processes 10;
    error_log logs/error.log error;
    #nginx worker 数量
    #指定错误日志文件路径
    
    #一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致.
    worker_rlimit_nofile 40000;
    events {
        worker_connections 1000;
    }
    http {
        default_type  application/json;
    # 设置默认 lua 搜索路径,添加 lua 路径 
        lua_package_path '/usr/local/lib/lua/?.lua;;'; 
    # 对于开发研究,可以对代码 cache 进行关闭,这样不必每次都重新加载 ngi nx。 
        lua_code_cache on; 
        
        
        server {
        
            listen 14001;
            location /test {
                content_by_lua_file test.lua;           
            }
        }
    }
    

    lua脚本

    --解析 body参数之前一定要先读取 body
    ngx.req.read_body()
    
    local data = ngx.req.get_body_data() 
    ngx.say("hello ", data) 
    

    命令

    # 首次启动
    openresty -p `pwd`
    # 重新启动
    sudo openresty -p `pwd`/ -c conf/nginx.conf -s reload
    

    golang

    go程序

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "net/http"
    )
    
    /*
     * 结构体属性首字母为大写,转换 json 才能成功,小写则不能
     * 结构体属性有 json 标签的,使用标签里面的字段名,否则为结构体属性名
     * 结构体属性有 json 标签的,注意标签里面的冒号后面没有空格,否则字段名仍为结构体属性名
     */
    type RespData struct {
        ClientId string `json:"clientId"`
        Username string `json:"username"`
        Password string `json:"password"`
    }
    
    // 处理application/json类型的POST请求
    func handlePostJson(writer http.ResponseWriter, request *http.Request) {
        // 根据请求body创建一个json解析器实例
        decoder := json.NewDecoder(request.Body)
    
        // 用于存放参数key=value数据
        var params map[string]string
    
        // 解析参数 存入map
        decoder.Decode(&params)
    
        var res RespData
        res.ClientId = params["clientId"]
        res.Username = params["username"]
        res.Password = params["password"]
        // fmt.Printf("POST json: username=%s, password=%s\n", res.username)
    
        res_json, err := json.Marshal(res)
        if err != nil {
            panic(err)
        }
        fmt.Printf("res_json=%s\n", string(res_json))
    
        fmt.Fprintf(writer, string(res_json))
    
    }
    
    func main() {
        http.HandleFunc("/test", handlePostJson)
    
        fmt.Println("Running at port 14002 ...")
    
        err := http.ListenAndServe(":14002", nil)
    
        if err != nil {
            log.Fatal("ListenAndServe: ", err.Error())
        }
    }
    
    
    

    对比结果

    最高tps 稳定性 语法 社区参考 新手上手时间 运维部署 集群
    openresty 59700 稳定数据 简单 足够(我比较熟) 1-2周 中等, 需要熟悉nginx 需要自实现
    golang 58800 最低到4万多, 暂未研究具体原因 简单 丰富 1-2天 无难度, 直接运行 需要自实现

    相关文章

      网友评论

          本文标题:简单对比openresty和go的性能

          本文链接:https://www.haomeiwen.com/subject/ipxdvdtx.html