首页 > 其他分享 >golang并发测试http demo

golang并发测试http demo

时间:2024-12-24 23:19:24浏览次数:3  
标签:rand http err demo fmt time golang Printf

package main

import (
	"bytes"
	"fmt"
	"math/rand"
	"net/http"
	"sync"
	"time"
)

const (
	url           = "http://127.0.0.1:8080"  // 请求的 URL
	ratePerSecond = 10                       // 每秒启动的并发数量
	duration      = 60                       // 持续时间,单位为秒
)

var (
	successCount int
	failCount    int
	totalLatency time.Duration
	mu           sync.Mutex
)

// Demo 测试数据生成
func generateTestData() string {
	// 随机用户ID
	userID := rand.Intn(10000) + 1

	// 随机行为事件
	events := []string{"login", "logout", "purchase", "view", "click", "like", "share", "comment"}
	event := events[rand.Intn(len(events))]

	// 随机设备类型
	devices := []string{"iPhone", "Android", "Windows PC", "MacBook", "iPad", "Smartwatch"}
	device := devices[rand.Intn(len(devices))]

	// 随机地理位置 (城市 + 国家)
	cities := []string{"New York", "London", "Tokyo", "Berlin", "Sydney", "Moscow", "Shanghai"}
	country := []string{"USA", "UK", "Japan", "Germany", "Australia", "Russia", "China"}
	location := fmt.Sprintf("%s, %s", cities[rand.Intn(len(cities))], country[rand.Intn(len(country))])

	// 随机时间戳
	timestamp := time.Now().Add(time.Duration(rand.Intn(100000)) * time.Second).Format(time.RFC3339)

	// 生成最终测试数据字符串
	testData := fmt.Sprintf(`{
		"user_id": %d,
		"event": "%s",
		"device": "%s",
		"location": "%s",
		"timestamp": "%s"
	}`, userID, event, device, location, timestamp)

	return testData
}

// 发送 POST 请求并记录统计数据
func sendPostRequest(client *http.Client, wg *sync.WaitGroup) {
	defer wg.Done()

	// 动态生成测试数据
	data := generateTestData()

	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	start := time.Now()
	resp, err := client.Do(req)
	latency := time.Since(start)

	mu.Lock()
	defer mu.Unlock()

	if err != nil {
		failCount++
		fmt.Printf("Error sending request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK {
		successCount++
		totalLatency += latency
		fmt.Println("Request successful")
	} else {
		failCount++
		fmt.Printf("Request failed with status: %d\n", resp.StatusCode)
	}
}

func main() {
	var wg sync.WaitGroup

	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	ticker := time.NewTicker(time.Second / time.Duration(ratePerSecond))
	defer ticker.Stop()

	endTime := time.Now().Add(time.Duration(duration) * time.Second)

	fmt.Println("Starting load test...")

	// 处理并发请求
	for time.Now().Before(endTime) {
		<-ticker.C
		wg.Add(1)
		go sendPostRequest(client, &wg)
	}

	// 等待所有请求完成
	wg.Wait()

	// 计算平均响应时间
	averageLatency := time.Duration(0)
	if successCount > 0 {
		averageLatency = totalLatency / time.Duration(successCount)
	}

	fmt.Printf("\n--- Test Summary ---\n")
	fmt.Printf("Total requests: %d\n", successCount+failCount)
	fmt.Printf("Successful requests: %d\n", successCount)
	fmt.Printf("Failed requests: %d\n", failCount)
	fmt.Printf("Average latency: %v\n", averageLatency)
	fmt.Println("Test completed.")
}

标签:rand,http,err,demo,fmt,time,golang,Printf
From: https://www.cnblogs.com/dujn/p/18628897

相关文章

  • golang中线程安全的map
    golang中线程安全的两种数据结构:channelsync.Map保证线程安全可以使用sync包下面的互斥锁sync.Mutex读写锁sync.RWMutex原子操作sync.atomicmap的底层原理count:key的数量flags:是否进行写操作B:桶的数量,它是以2为底的对数,即2的B次方hash0:哈希因子buckets:桶的列表,一个bma......
  • Forest框架 访问HTTPS协议
    问题描述第三方接口使用的是HTTPS协议,导致程序一直报错找不到协议请求超时 解决方案Forest的单向验证的默认协议为TLS,将ssl-protocol属性修改为其它协议forest:...ssl-protocol:SSL使用HTTPS协议时,不能只用ip地址,必须使用域名@Get(url="https://bjdx.wdm......
  • 鸿蒙学习记录之http网络请求
    权限申请路径为:entry->src->main->module.json5"requestPermissions":[{"name":"ohos.permission.INTERNET",}]基本使用//1.引入包名import{http}from'@kit.NetworkKit';//2.创建一个Htt......
  • ESP32 HTTP Client 报错'Error parse url'
    ESP32HTTPClient报错今天在使用ESP32中的esp_http_client_init如下//结构体typedefstruct{charurl[256];}config_t;//主要代码strncpy(config.url,"http://xxx/xxx",sizeof(config.url)-1);config.url[sizeof(config.url)-1]='\0';//确保字符串以空......
  • 使用http请求触发jenkins构建
    我的需求:每当有一个post请求发送,触发我jenkins的一个构建,生成一个新docker实例。安装jenkins使用docker构建镜像:https://docker.unsee.techdockerpulljenkins/jenkins:ltsmkdir-p~/jenkins_homesudochown1000:1000~/jenkins_home启动dockerrun-d-p8080:808......
  • 低版本Android发送https请求,Android4.4.2启用TLSv1.2,Android4.4.2发送https请求报错,An
    参考:https://blog.csdn.net/weixin_54087854/article/details/134625241https://blog.csdn.net/weixin_35647799/article/details/117684065Android4.4.2发送https请求时,出现错误:javax.net.ssl.SSLProtocolException:SSLhandshakeaborted:ssl=0xb7eabc88:FailureinSSLlibr......
  • 移动解析HttpDNS
    移动解析HttpDNS从基础库2.19.2开始支持开发者调用wx.request时,可以开启移动解析HttpDNS服务。该服务基于Http协议向服务商的DNS服务器发送域名解析请求,替代了基于DNS协议向运营商LocalDNS发起解析请求的传统方式,可以避免LocalDNS造成的域名劫持和跨网访问问题,解决移动互联......
  • XMLHttpRequest的基础知识
    get请求 constxml=newXMLHttpRequest();xml.open("GET","https://jsonplaceholder.typicode.com/todos/1",true);xml.onreadystatechange=function(){if(xml.readyState===4&&xml.status===200){console.log(xml.re......
  • php网络编程swoole http
    服务端:<?phpuseSwoole\Http\Server;useSwoole\Http\Request;useSwoole\Http\Response;//创建HTTP服务器$server=newServer('127.0.0.1',9501);$server->on('start',function($server){//print_r($server);echo&qu......
  • python网络编程之http longpull
    服务端:fromflaskimportFlask,request,jsonifyimporttimeapp=Flask(__name__)@app.route('/stream',methods=['GET'])defpoll():#假设这里有一个方法来检查是否有新数据#为了示例,我们简单地模拟等待数据time.sleep(5)#模拟处理时间或等待......