client-go 和 golang 原始碼中的技巧
阿新 • • 發佈:2021-09-28
參考連結:https://www.cnblogs.com/charlieroro/p/11112526.html
1.實現了對golang map的key的處理,如計算交集,並集等。
package main import ( "fmt" "k8s.io/apimachinery/pkg/util/sets" ) func main(){ map1 := map[string]int{"aaa":1,"bbb":2,"ccc":3} map2 := map[string]int{"ccc":1,"ddd":2,"eee":3} newmap1 := sets.StringKeySet(map1) newmap2 := sets.StringKeySet(map2) fmt.Println(newmap1.List(),newmap2.List()) fmt.Println(newmap1.HasAny(newmap2.List()...)) //3個點用於把陣列打散為單個元素 }結果:true
2.k8s.io/apimachinery/pkg/util/wait/wait.go
函式:func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error
ExponentialBackoff : 可以實現在函式執行錯誤後實現以指數退避方式的延時重試。ExponentialBackoff內部使用的是time.Sleep
ExponentialBackoff的首個入參Backoff如下:
- Duration:表示初始的延時時間
- Factor:指數退避的因子
- Jitter:可以看作是偏差因子,該值越大,每次重試的延時的可選區間越大
- Steps:指數退避的步數,可以看作程式的最大重試次數
- Cap:用於在Factor非0時限制最大延時時間和最大重試次數,為0表示不限制最大延時時間
type Backoff struct { // The initial duration. Duration time.Duration // Duration is multiplied by factor each iteration. Must be greater// than or equal to zero. Factor float64 // The amount of jitter applied each iteration. Jitter is applied after // cap. Jitter float64 // The number of steps before duration stops changing. If zero, initial // duration is always used. Used for exponential backoff in combination // with Factor. Steps int // The returned duration will never be greater than cap *before* jitter // is applied. The actual maximum cap is `cap * (1.0 + jitter)`. Cap time.Duration }
當Factor和Jitter都為0時,可以看到排程週期是相同的,即Duration的值(1s)。
import ( "fmt" "k8s.io/apimachinery/pkg/util/wait" "time" ) func main(){ var DefaultRetry = wait.Backoff{ Steps: 5, Duration: 1 * time.Second, Factor: 0, Jitter: 0, } fmt.Println(wait.ExponentialBackoff(DefaultRetry,func() (bool, error){ fmt.Println(time.Now()) return false,nil })) } 結果: 2019-07-05 10:17:33.9610108 +0800 CST m=+0.079831101 2019-07-05 10:17:34.961132 +0800 CST m=+1.079952301 2019-07-05 10:17:35.961512 +0800 CST m=+2.080332301 2019-07-05 10:17:36.9625144 +0800 CST m=+3.081334701 2019-07-05 10:17:37.9636334 +0800 CST m=+4.082453701 timed out waiting for the condition