机器配置:
1个物理CPU:
4核:
8个逻辑CPU:
15GB内存
1 写一个goweb
main.go
package mainimport ( "encoding/json" "fmt" "log" "net/http" "strings" ) // 处理一个普通的POST请求,将请求包体原样输出 func readBody(w http.ResponseWriter, r *http.Request) { mapA := map[string]int{"year": 123, "age": 90} //map值mapB, _ := json.Marshal(mapA)w.Write(mapB)return}func main() {http.HandleFunc("/submit", readBody) //设置访问的路由err := http.ListenAndServe(":9090", nil) //设置监听的端口if err != nil {log.Fatal("ListenAndServe: ", err)}}
启动go 服务只需要执行以下命令。
go run main.go
而centOS 下安装GO也非常容易:
step1: 使用wget下载go二进制包:
yum install wget -y
wget https://golang.org/dl/go1.17.2.linux-amd64.tar.gz3
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.17.2.linux-amd64.tar.gz
将go写入环境变更
vi /etc/profilesource /etc/profile
export PATH=$PATH:/usr/local/go/bin
go version
所占用的体积非常小。 编译后的文件仅7.4MB。 相对于java工程无论是启动速度、内存占用、部署复杂度都更胜一筹。
2 使用压测工具Locust
2.1 压测脚本
behavior.py
from locust import task, FastHttpUser
import time
import json
class MyUser(FastHttpUser):
@task
def index(self):
data = {"total_fee":"1","business_order_id": "1234567890ABCDEFG"}
body = json.dumps(data)
headers={'Content-Type':'application/json'}
response = self.client.post('/submit', headers=headers, data=body)
print(response.json())
time.sleep(0.001)
2.2 启动脚本
locust -f behavior.py --host=http://XX.XX.XX.146:9090
2.3 WEB 界面查看压测实状
3 压测结论
go-web 在普通云主机(4核、16GB) 的压测表现在 QPS 3000左右。 即 每秒处理 3000个请求。
而JAVA WEB在相同的主机环境下压测表现仅达 QPS 300左右。
go 作为一种分布式新型语言较传统的java具有更大优势,具有内存占用小、启动速度快、运维部署简单、高性能高并发的特点。随着云原生技术的兴起,go语言作为载体的工具、分布式中间件、web应用出现在各种技术解决方案中。