userbelieve123 发表于 2024-7-22 10:05

lylswb 发表于 2024-7-22 10:54

package main

import (
        "fmt"
        "io/ioutil"
        "log"
        "math/rand"
        "net/http"
        "sync"
        "time"
)
func pressureTest(url string, concurrency int, requests int, wg *sync.WaitGroup) {
        defer wg.Done()
        client := &http.Client{}

        for i := 0; i < requests; i++ {
                start := time.Now()

                resp, err := client.Get(url)
                if err != nil {
                        log.Printf("Error making request: %v", err)
                        continue
                }
                defer resp.Body.Close()

                body, err := ioutil.ReadAll(resp.Body)
                if err != nil {
                        log.Printf("Error reading response body: %v", err)
                        continue
                }

                duration := time.Since(start)
                fmt.Printf("Request #%d took %v. Response: %s\n", i+1, duration, body)
                time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) // 防止被目标服务器封禁
        }
}
调用
func main() {
        url := "http://example.com" // 目标URL
        concurrency := 100          // 并发数
        requestsPerClient := 100    // 每个goroutine发送的请求数

        var wg sync.WaitGroup
        wg.Add(concurrency)

        for i := 0; i < concurrency; i++ {
                go pressureTest(url, concurrency, requestsPerClient, &wg)
        }

        wg.Wait()
}

艾莉希雅 发表于 2024-7-22 12:03

你可以参考这个项目
https://github.com/myzhan/boomer

jypony 发表于 2024-7-22 12:10

https://github.com/link1st/go-stress-testing
这个也不错

userbelieve123 发表于 2024-7-22 13:24

页: [1]
查看完整版本: go语言怎么写一个压测的服务