package main
import (
"errors"
"fmt"
"time"
)
type CircuitBreaker struct {
isOpen bool
failureCount int
threshold int
timeout time.Duration
lastAttempt time.Time
}
func NewCircuitBreaker(threshold int, timeout time.Duration) *CircuitBreaker {
return &CircuitBreaker{
threshold: threshold,
timeout: timeout,
}
}
func (cb *CircuitBreaker) Call(do func() error) error {
if cb.isOpen && time.Since(cb.lastAttempt) < cb.timeout {
return errors.New("circuit is open, call failed")
}
err := do()
if err != nil {
cb.failureCount++
cb.lastAttempt = time.Now()
if cb.failureCount >= cb.threshold {
cb.isOpen = true
return errors.New("circuit opened due to failure")
}
return err
}
cb.failureCount = 0
cb.isOpen = false
return nil
}
func main() {
cb := NewCircuitBreaker(3, 5*time.Second)
for i := 0; i < 10; i++ {
err := cb.Call(func() error {
// Simulate a faulty service call:
if time.Now().Second()%2 == 0 {
return errors.New("simulated service failure")
}
fmt.Println("Service call succeeded")
return nil
})
if err != nil {
fmt.Println(err)
time.Sleep(1 * time.Second) // Wait before retrying
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?