Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkg/app/client/discovery/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,6 @@
// the instance list can/should be cached and CacheKey can be used to map the instance list in cache.
type Result struct {
CacheKey string
HashKey string // HashKey is used for consistent hash balancer to select instance

Check failure on line 111 in pkg/app/client/discovery/discovery.go

View workflow job for this annotation

GitHub Actions / lint

File is not properly formatted (goimports)
Instances []Instance
}
10 changes: 9 additions & 1 deletion pkg/app/client/loadbalance/lbcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,15 @@ func (b *BalancerFactory) GetInstance(ctx context.Context, req *protocol.Request
return nil, err
}
atomic.StoreInt32(&cacheRes.expire, 0)
ins := b.balancer.Pick(cacheRes.res.Load().(discovery.Result))

res := cacheRes.res.Load().(discovery.Result)

// Set HashKey from request if HashKeyFunc is configured
if b.opts.HashKeyFunc != nil {
res.HashKey = b.opts.HashKeyFunc(ctx, req)
}

ins := b.balancer.Pick(res)
if ins == nil {
hlog.SystemLogger().Errorf("null instance. serviceName: %s, options: %v", string(req.Host()), req.Options())
return nil, errors.NewPublic("instance not found")
Expand Down
6 changes: 6 additions & 0 deletions pkg/app/client/loadbalance/loadbalance.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
package loadbalance

import (
"context"
"time"

"github.com/cloudwego/hertz/pkg/app/client/discovery"
"github.com/cloudwego/hertz/pkg/protocol"
)

// Loadbalancer picks instance for the given service discovery result.
Expand Down Expand Up @@ -55,6 +57,10 @@ type Options struct {
// Balancer expire check interval
// we need remove idle Balancers for resource saving
ExpireInterval time.Duration

// HashKeyFunc is used to extract hash key from request for consistent hash balancer.
// If set, this function will be called to determine the hash key used by consistent hash balancer.
HashKeyFunc func(ctx context.Context, req *protocol.Request) string
}

// Check checks option's param
Expand Down
Loading