This commit is contained in:
JACKYMYPERSON
2025-09-13 20:00:34 +08:00
parent f83b78dffb
commit 0fb5b70505

90
oneKUsers/mian.go Normal file
View File

@@ -0,0 +1,90 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"sync"
)
// 请求体结构
type UserRequest struct {
UserID int `json:"user_id"`
}
// 响应体结构(根据实际接口响应调整)
type Response struct {
Success bool `json:"success"`
Message string `json:"message"`
}
func main() {
const totalUsers = 1000 // 总用户数
const concurrencyLimit = 100 // 并发控制,避免过多同时连接
// 创建信号量控制并发数量
semaphore := make(chan struct{}, concurrencyLimit)
var wg sync.WaitGroup
for i := 1; i <= totalUsers; i++ {
wg.Add(1)
semaphore <- struct{}{} // 获取信号量
go func(userID int) {
defer wg.Done()
defer func() { <-semaphore }() // 释放信号量
// 发送POST请求
result, err := sendPostRequest(userID)
if err != nil {
fmt.Printf("用户 %d 请求失败: %v\n", userID, err)
return
}
// 输出结果
fmt.Printf("用户 %d 响应: %+v\n", userID, result)
}(i)
}
// 等待所有请求完成
wg.Wait()
fmt.Println("所有请求已完成")
}
// 发送POST请求
func sendPostRequest(userID int) (*Response, error) {
url := "http://localhost:9096/user/kill"
// 创建请求体
requestBody := UserRequest{
UserID: userID,
}
// 转换为JSON
jsonBody, err := json.Marshal(requestBody)
if err != nil {
return nil, fmt.Errorf("JSON序列化失败: %v", err)
}
// 发送POST请求
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonBody))
if err != nil {
return nil, fmt.Errorf("请求发送失败: %v", err)
}
defer resp.Body.Close()
// 检查响应状态码
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("响应状态码异常: %d", resp.StatusCode)
}
// 解析响应
var response Response
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&response); err != nil {
return nil, fmt.Errorf("响应解析失败: %v", err)
}
return &response, nil
}