feat: consistent hash balancer support (#5246)

Co-authored-by: 周曙光 <zsg@zhoushuguangdeMacBook-Pro.local>
This commit is contained in:
zhoushuguang
2025-10-19 22:10:30 +08:00
committed by GitHub
parent 568f9ce007
commit e30317e9c4
7 changed files with 343 additions and 4 deletions

View File

@@ -12,6 +12,8 @@ import (
"github.com/zeromicro/go-zero/core/discov"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/internal/mock"
"github.com/zeromicro/go-zero/zrpc/internal/balancer/consistenthash"
"github.com/zeromicro/go-zero/zrpc/internal/balancer/p2c"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
@@ -245,3 +247,42 @@ func TestNewClientWithTarget(t *testing.T) {
assert.NotNil(t, err)
}
func TestMakeLBServiceConfig(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "empty name uses default p2c",
input: "",
expected: fmt.Sprintf(`{"loadBalancingPolicy":"%s"}`, p2c.Name),
},
{
name: "custom balancer name",
input: "consistent_hash",
expected: `{"loadBalancingPolicy":"consistent_hash"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := makeLBServiceConfig(tt.input)
if got != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, got)
}
})
}
}
func TestSetHashKey(t *testing.T) {
ctx := context.Background()
key := "abc123"
ctx = SetHashKey(ctx, key)
got := consistenthash.GetHashKey(ctx)
assert.Equal(t, key, got)
assert.Empty(t, consistenthash.GetHashKey(context.Background()))
}