feat: 添加 Session 亲和路由支持(NewSession / WithAffinity)

- 新增 NewSession(pool):返回固定到同一 worker 进程的 Pool 视图
- 新增 WithAffinity(ctx, key):相同 key 通过 FNV hash 稳定路由到同一 worker
- pool.acquire 支持亲和路由,无亲和时保持轮询
- example 添加 Session / WithAffinity / 全局变量共享三组演示
This commit is contained in:
2026-05-08 11:21:02 +08:00
parent 30004e44ee
commit cda662e874
5 changed files with 209 additions and 1 deletions

26
affinity.go Normal file
View File

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