descripción incorrecta
- Creó un script en el proyecto go y escribió una función principal
- que utiliza un modelo
github.com/link1st/go-stress-testing/stress
import (
"fmt"
// "github.com/dji/go-stress-testing/stress"
"github.com/link1st/go-stress-testing/stress"
"net/http"
"time"
)
- Al ejecutar
go run xxx.go
se reporta un error
queries.go:6:2: no required module provides package github.com/link1st/go-stress-testing/stress; to add it:
go get github.com/link1st/go-stress-testing/stress
- Indicación para usar
go get github.com/link1st/go-stress-testing/stress
el comando para descargar los módulos que faltan - Efectivamente, el error aún se informa después de la ejecución.
go: github.com/link1st/go-stress-testing/stress: no matching versions for query "upgrade"
- Indica que no hay una versión más nueva disponible para el módulo
- Versión especificada:
go get github.com/link1st/go-stress-testing/stress@latest
- Sigo recibiendo un error de que no se puede obtener la versión de destino
Busque información sobre la versión del módulo en github
- Las técnicas de búsqueda
language:go model_name
son las siguientes - Ver información de la versión del módulo
Especificar la versión a instalar
go get github.com/link1st/go-stress-testing/stress@v1.0.5
- Las cosas no siempre van bien, todavía reportan errores
go: github.com/link1st/go-stress-testing/[email protected]: invalid version: unknown revision stress/v1.0.5
Construcción manual
- Después de consultar la información, puede compilar manualmente el proyecto para instalar el módulo, similar a la biblioteca de terceros en el proyecto maven
- En primer lugar, averigüe dónde están instalados los módulos dependientes del proyecto go
- bajo
$GOPATH/pkg/mod/
el directorio - Similar al directorio .m2 del repositorio local de maven. La estructura de almacenamiento del módulo también es similar.
- bajo
- A continuación, descargue
github.com/link1st/go-stress-testing/stress
el código fuente del proyecto de- El código clonado por defecto es la rama maestra
git checkout v1.0.5
- próximo
go build
- -o: especifica el nombre y la ruta del archivo de salida.
- -v: Imprime el nombre del paquete Go compilado.
- -a: fuerza la recompilación de todos los paquetes sin usar los resultados almacenados en caché.
- -carrera: permite que el detector de carreras de datos identifique e informe carreras de datos en los programas Go.
- -tags: especifica las etiquetas de compilación que se usarán.
- comando completo
go build -o /Users/duzhihao/go/pkg/mod/github.com/link1st/go-stress-testing/[email protected] main.go
- Pero todavía no funciona
raíz del problema
- El paquete requerido es
github.com/link1st/go-stress-testing/stress
- Sea claro acerca de cómo interpretar este paquete
github.com
: El módulo proviene de githublink1st
: El autor es link1stgo-stress-testing
: Pertenece al proyecto go-stress-testingstress
: El módulo de estrés bajo el proyecto
- Vaya al proyecto github para encontrar este módulo
- Buen chico, no hay módulo de estrés en absoluto.
solución final
Encontré el código fuente en el módulo de estrés por otros medios, y hay cuatro archivos en total.
tarea.ir
package stress
import (
"context"
"errors"
)
// Task represents a stress testing task, which consists of a name, a RunFunc function and optional StopFunc function
type Task struct {
Name string
RunFunc func() error
StopFunc func() error
Context context.Context
Cancel context.CancelFunc
}
// Run runs the Task and returns a TestResult
func (t *Task) Run() *TestResult {
var requests uint64
var errors uint64
for {
select {
case <-t.Context.Done():
return &TestResult{
Requests: requests,
Errors: errors,
}
default:
if err := t.RunFunc(); err != nil {
errors++
}
requests++
}
}
}
// NewTask returns a new Task with the given name and RunFunc function
func NewTask(name string, runFunc func() error) *Task {
ctx, cancel := context.WithCancel(context.Background())
return &Task{
Name: name,
RunFunc: runFunc,
Context: ctx,
Cancel: cancel,
}
}
// NewTimedTask returns a new Task with the given name, RunFunc function and duration
func NewTimedTask(name string, runFunc func() error, duration int) *Task {
ctx, cancel := context.WithTimeout(context.Background(), Duration(duration)*time.Second)
return &Task{
Name: name,
RunFunc: runFunc,
StopFunc: cancel,
Context: ctx,
Cancel: cancel,
}
}
// Stop stops the Task
func (t *Task) Stop() error {
if t.StopFunc == nil {
return errors.New("Stop function is not defined")
}
return t.StopFunc()
}
escena.ir
package stress
import (
"sync"
"sync/atomic"
"time"
)
// Scene represents a stress testing scene, which consists of multiple tasks
type Scene struct {
Name string
Frequency time.Duration
Duration time.Duration
SetupFunc func() error
CleanupFunc func() error
tasks []*Task
}
// AddTask adds a new Task to the Scene
func (s *Scene) AddTask(task *Task) {
s.tasks = append(s.tasks, task)
}
// Run runs the Scene and returns a TestResult
func (s *Scene) Run() *TestResult {
resCh := make(chan *TestResult)
wg := sync.WaitGroup{
}
wg.Add(len(s.tasks))
for _, task := range s.tasks {
go func(task *Task) {
defer wg.Done()
resCh <- task.Run()
}(task)
}
if s.SetupFunc != nil {
if err := s.SetupFunc(); err != nil {
panic(err)
}
}
ticker := time.NewTicker(s.Frequency)
stop := make(chan bool)
go func() {
time.Sleep(s.Duration)
close(stop)
}()
var requests uint64
var errors uint64
loop:
for {
select {
case <-ticker.C:
for _, task := range s.tasks {
for i := 0; i < requestsPerTask; i++ {
if err := task.RunFunc(); err != nil {
atomic.AddUint64(&errors, 1)
}
atomic.AddUint64(&requests, 1)
}
}
case res := <-resCh:
atomic.AddUint64(&requests, res.Requests)
atomic.AddUint64(&errors, res.Errors)
case <-stop:
break loop
}
}
ticker.Stop()
if s.CleanupFunc != nil {
if err := s.CleanupFunc(); err != nil {
panic(err)
}
}
wg.Wait()
elapsed := time.Duration(requests) * time.Second / time.Duration(rps)
return &TestResult{
Requests: requests,
Errors: errors,
Rps: rps,
Elapsed: elapsed,
}
}
// NewScene returns a new Scene with the given name and default settings
func NewScene(name string) *Scene {
return &Scene{
Name: name,
Frequency: time.Second,
Duration: 10 * time.Second,
SetupFunc: func() error {
return nil
},
CleanupFunc: func() error {
return nil
},
}
}
prueba_resultado.ir
package stress
import "time"
// TestResult represents the result of a stress test
type TestResult struct {
Requests uint64
Errors uint64
Rps uint64
Elapsed time.Duration
}
utils.go
package stress
import "time"
const (
requestsPerTask = 100
rps = 100
)
// Duration is an int that can be used with the time package
type Duration int
func (d Duration) String() string {
return time.Duration(d * time.Second).String()
}
Cabe señalar que los códigos de estos archivos go no son fiables y es necesario realizar una adaptación lógica de acuerdo con los requisitos de las aplicaciones prácticas.