refactor: 将 WithAffinity 重命名为 WithSticky,文件 affinity.go → sticky.go

This commit is contained in:
2026-05-08 11:37:34 +08:00
parent 3d293699e9
commit a3cf983b39
4 changed files with 34 additions and 34 deletions

26
sticky.go Normal file
View File

@@ -0,0 +1,26 @@
package gobridge
import (
"context"
"hash/fnv"
)
type stickyKey struct{} // 用户提供的字符串 keyacquire 时 hash 到 worker 下标
// WithSticky 将粘性键写入 ctx相同 key 始终路由到同一 worker 进程。
//
// ctx = gobridge.WithSticky(ctx, "user-42")
// gobridge.Invoke(ctx, pool, "method", ...) // 同 key 始终走同一进程
func WithSticky(ctx context.Context, key string) context.Context {
return context.WithValue(ctx, stickyKey{}, key)
}
// workerIndexFor 根据 ctx 计算应使用的 worker 下标,无粘性键时返回 -1交由轮询
func workerIndexFor(ctx context.Context, n int) int {
if key, ok := ctx.Value(stickyKey{}).(string); ok && key != "" {
h := fnv.New32a()
h.Write([]byte(key))
return int(h.Sum32()) % n
}
return -1
}