一个由golang代码构成的简易断路器

200 阅读1分钟

tfgo-breaker

1.介绍

这是一个由Golang代码组成的简单的断裂器。你可以在你的项目中快速使用它。
支持函数中断、超时、自动干运行。

2.演示

    func main() {
        myNormalLogic := normalLogic
        myBreakerLogic := breakerLogic
        // create a new breaker
        breakerConf1 := NewBreakConf("test-breaker-1", 2, 20*time.Second, 2, myNormalLogic, myBreakerLogic)
        breaker1 := NewBreaker(breakerConf1)
	    for i := 0; i < 100; i++ {
            r, _ := rand.Int(rand.Reader, big.NewInt(2))
            res, err := breaker1.Run(r.Int64())
            fmt.Println("breakerRun:", res, err)
            time.Sleep(1 * time.Second)
	    }
    }

    func normalLogic(request interface{}) (interface{}, error, bool) {
    	// our normal logic
    	if request.(int64) == 1 {
    		errMsg := "normal logic err"
    		return request, errors.New(errMsg), false
    	}
    	return "normal logic success", nil, true
    }
    
    func breakerLogic(request interface{}) (interface{}, error) {
    	// our breaker logic
    	return "this is breaker logic", nil
    }

3.注意事项

我们的断路器应该阻止一个进程或一个函数

4. 断路器的权限

标题描述缺省
名称断路器名称。一个业务流程或功能有一个断路器。
阈值断路器次数达到该值时,断路器将打开。500
过期断路器钥匙的过期时间。5分钟
干运行百分比当断路器打开时,有%的请求可以通过断路器,如果其中一个成功,断路器将关闭。(例如:10:1/10 5:1/5 2:1/2)10%
回调函数(CallBackFunc正常的业务逻辑。当断路器被关闭时,将运行它
断路器功能断路器的业务逻辑。当断路器被打开时,将运行它。

GitHub

github.com/tfcp/tfgo-b…