Skip to content

Instantly share code, notes, and snippets.

@dcaba
Created June 30, 2020 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcaba/f3e64d989de5b5cc89a63d1b27721d6c to your computer and use it in GitHub Desktop.
Save dcaba/f3e64d989de5b5cc89a63d1b27721d6c to your computer and use it in GitHub Desktop.
Playing with a circuit breaker - cep21/circuit
package main
import (
"context"
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/cep21/circuit/metriceventstream"
"github.com/cep21/circuit/metrics/rolling"
"github.com/cep21/circuit/v3"
"github.com/cep21/circuit/v3/closers/hystrix"
)
func main() {
sf := rolling.StatFactory{}
h := circuit.Manager{
DefaultCircuitProperties: []circuit.CommandPropertiesConstructor{sf.CreateConfig},
}
es := metriceventstream.MetricEventStream{
Manager: &h,
}
go func() {
if err := es.Start(); err != nil {
log.Fatal(err)
}
}()
// ES is a http.Handler, so you can pass it directly to your mux
http.Handle("/hystrix.stream", &es)
go func() {
log.Fatal(http.ListenAndServe(":8080", nil))
}()
// Create a circuit with a unique name
config := circuit.Config{
General: circuit.GeneralConfig{
ClosedToOpenFactory: hystrix.OpenerFactory(hystrix.ConfigureOpener{ErrorThresholdPercentage: 50}),
OpenToClosedFactory: hystrix.CloserFactory(hystrix.ConfigureCloser{RequiredConcurrentSuccessful: 2}),
},
}
c := h.MustCreateCircuit("hello-world", config)
rand.Seed(time.Now().UnixNano())
for {
errResult := c.Execute(context.Background(), func(ctx context.Context) error {
time.Sleep(time.Millisecond * 550)
if rand.Intn(2) == 0 {
return nil
}
return fmt.Errorf("an error")
}, nil)
fmt.Println("Result of execution:", errResult)
}
if err := es.Close(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment