1
0
mirror of https://github.com/go-kratos/kratos.git synced 2026-05-22 10:15:24 +02:00

Feat: add load balancer (#1437)

* add balancer
* add p2c balancer
* add http client selector filter

Co-authored-by: yuemoxi <99347745@qq.com>
Co-authored-by: chenzhihui <zhihui_chen@foxmail.com>
This commit is contained in:
longxboy
2021-09-12 15:14:21 +08:00
committed by GitHub
parent 0184d217cf
commit 20f0a07d36
20 changed files with 796 additions and 140 deletions
+52
View File
@@ -0,0 +1,52 @@
package direct
import (
"context"
"sync/atomic"
"time"
"github.com/go-kratos/kratos/v2/selector"
)
const (
defaultWeight = 100
)
var (
_ selector.WeightedNode = &node{}
_ selector.WeightedNodeBuilder = &Builder{}
)
// node is endpoint instance
type node struct {
selector.Node
// last lastPick timestamp
lastPick int64
}
// Builder is direct node builder
type Builder struct{}
// Build create node
func (*Builder) Build(n selector.Node) selector.WeightedNode {
return &node{Node: n, lastPick: 0}
}
func (n *node) Pick() selector.DoneFunc {
now := time.Now().UnixNano()
atomic.StoreInt64(&n.lastPick, now)
return func(ctx context.Context, di selector.DoneInfo) {}
}
// Weight is node effective weight
func (n *node) Weight() float64 {
if n.InitialWeight() != nil {
return float64(*n.InitialWeight())
}
return defaultWeight
}
func (n *node) PickElapsed() time.Duration {
return time.Duration(time.Now().UnixNano() - atomic.LoadInt64(&n.lastPick))
}