Grabar un registro de pasos de un proyecto go

descripción incorrecta

  • Creó un script en el proyecto go y escribió una función principal
  • que utiliza un modelogithub.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.gose 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/stressel 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_nameson las siguientes
    • imagen.png
  • Ver información de la versión del módulo
  • imagen.png

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

  1. En primer lugar, averigüe dónde están instalados los módulos dependientes del proyecto go
    1. bajo $GOPATH/pkg/mod/el directorio
    2. Similar al directorio .m2 del repositorio local de maven. La estructura de almacenamiento del módulo también es similar.
  2. A continuación, descargue github.com/link1st/go-stress-testing/stressel código fuente del proyecto de
    1. El código clonado por defecto es la rama maestra
    2. git checkout v1.0.5
  3. próximogo 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.
  4. comando completogo build -o /Users/duzhihao/go/pkg/mod/github.com/link1st/go-stress-testing/[email protected] main.go
    1. Pero todavía no funciona

raíz del problema

  1. El paquete requerido esgithub.com/link1st/go-stress-testing/stress
  2. Sea claro acerca de cómo interpretar este paquete
    1. github.com: El módulo proviene de github
    2. link1st: El autor es link1st
    3. go-stress-testing: Pertenece al proyecto go-stress-testing
    4. stress: El módulo de estrés bajo el proyecto
  3. Vaya al proyecto github para encontrar este módulo
  4. imagen.png
  5. 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.

Supongo que te gusta

Origin blog.csdn.net/GoNewWay/article/details/130997639
Recomendado
Clasificación