Documentation
¶
Index ¶
- Variables
- func DestroyAllGroups()
- func DestroyGroup(name string) bool
- func ListGroups() []string
- type ByteView
- type Cache
- func (c *Cache) Add(key string, value ByteView)
- func (c *Cache) AddWithExpiration(key string, value ByteView, expirationTime time.Time)
- func (c *Cache) Clear()
- func (c *Cache) Close()
- func (c *Cache) Delete(key string) bool
- func (c *Cache) Get(ctx context.Context, key string) (value ByteView, ok bool)
- func (c *Cache) Len() int
- func (c *Cache) Stats() map[string]interface{}
- type CacheOptions
- type Client
- type ClientOption
- type ClientOptions
- type ClientPicker
- type Getter
- type GetterFunc
- type Group
- type GroupOption
- type Peer
- type PeerPicker
- type PickerOption
- type Server
- func (s *Server) Delete(ctx context.Context, req *proto.DeleteRequest) (*proto.DeleteResponse, error)
- func (s *Server) Get(ctx context.Context, req *proto.GetRequest) (*proto.GetResponse, error)
- func (s *Server) Set(ctx context.Context, req *proto.SetRequest) (*proto.SetResponse, error)
- func (s *Server) Start() error
- func (s *Server) Stop()
- type ServerOption
- func WithAdvertiseAddr(addr string) ServerOption
- func WithDialTimeout(timeout time.Duration) ServerOption
- func WithEtcdEndpoints(endpoints []string) ServerOption
- func WithServerAuthToken(token string) ServerOption
- func WithStatsAddr(addr string) ServerOption
- func WithTLS(certFile, keyFile string) ServerOption
- type ServerOptions
Constants ¶
This section is empty.
Variables ¶
var DefaultServerOptions = &ServerOptions{ EtcdEndpoints: []string{"localhost:2379"}, DialTimeout: 5 * time.Second, MaxMsgSize: 4 << 20, }
DefaultServerOptions 返回服务端默认配置:etcd 本地端点、5 秒超时、4MB 消息限制。
var ErrGroupClosed = errors.New("cache group is closed")
ErrGroupClosed 表示操作的目标 Group 已关闭。
var ErrKeyRequired = errors.New("key is required")
ErrKeyRequired 表示操作需要非空的 key。
var ErrValueRequired = errors.New("value is required")
ErrValueRequired 表示 Set 操作需要非空的 value。
Functions ¶
func DestroyGroup ¶
DestroyGroup 关闭 Group 并从全局注册表移除。先 close() 再 delete(groups, name)。 close 不自行删除注册表条目,避免锁重入死锁。
Types ¶
type ByteView ¶
type ByteView struct {
// contains filtered or unexported fields
}
ByteView 是只读字节视图,作为 ReachCache 中缓存值的统一类型。
通过双层深拷贝机制保证数据不可变:
- 存储时深拷贝:外部原始切片可安全修改而不影响缓存
- 读取时深拷贝:ByteSlice() 返回副本,调用方修改不影响缓存原始数据
ByteView 实现了 store.Value 接口(Len()),可无缝集成到 Store 存储引擎。
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache 是对底层 store.Store 的并发安全封装,提供懒加载初始化、ByteView 类型适配和统计信息。
锁约定:
- 读锁(RLock):保护 Get / Add / AddWithExpiration / Delete / Len
- 写锁(Lock):保护 Clear / Close(含 ensureInitialized 中的首次初始化)
关闭保护策略(防止 TOCTOU 竞态):
- 入口快速检查:atomic.LoadInt32(&c.closed) 无锁快速拒绝
- 持锁后二次校验:获取 mu 锁后再次检查 closed,消除 Close() 在锁空窗期 将 c.store 置 nil 的竞态窗口,保证访问 c.store 时引用有效
生命周期:
- 创建:NewCache(opts) → 仅保存配置,不分配 Store
- 首次写入:Add → ensureInitialized() → 双重检查锁定创建 Store
- 关闭:Close() → CompareAndSwap 关闭标记 → 释放 Store → 重置 initialized
func NewCache ¶
func NewCache(opts CacheOptions) *Cache
NewCache 创建一个未初始化的 Cache 实例(仅保存配置)。 底层 Store 在首次 Add 时通过 ensureInitialized 懒加载创建。
func (*Cache) Add ¶
Add 向缓存中写入 ByteView,永不过期。若 Cache 已关闭则静默忽略。 首次 Add 会触发 ensureInitialized 懒加载创建底层 Store。
func (*Cache) AddWithExpiration ¶
AddWithExpiration 向缓存中写入带过期时间的 ByteView。 若 expirationTime 已过期则跳过写入。
func (*Cache) Clear ¶
func (c *Cache) Clear()
Clear 清空缓存中的所有数据并重置 hits/misses 统计。 已关闭或未初始化的 Cache 静默忽略。使用写锁(Lock)确保期间无并发读写。
func (*Cache) Close ¶
func (c *Cache) Close()
Close 关闭缓存。使用 CompareAndSwap 保证幂等。 关闭动作:CAS 设 closed=1 → 写锁 → 关闭底层 Store → store=nil → initialized=0。 注意 Close 不自动清空数据,调用前应先 Clear 以触发 OnEvicted 回调。
func (*Cache) Get ¶
Get 从缓存中获取值。
执行路径:
- 检查 closed:已关闭 → 返回 (ByteView{}, false)
- 检查 initialized:未初始化 → misses++ → 返回 (ByteView{}, false)
- 获取读锁 → 再次检查 closed(防止 TOCTOU 竞态:Close 可能在步骤 2~3 之间释放 store)
- store.Get(key) → 命中 → hits++ → 类型断言为 ByteView → 返回
- 未命中或类型断言失败 → misses++ → 返回 (ByteView{}, false)
注意 Get 不会触发懒初始化——未初始化的 Cache 永远返回未命中。
type CacheOptions ¶
type CacheOptions struct {
CacheType store.CacheType // LRU 或 LRU2
MaxBytes int64 // 最大内存字节数
BucketCount uint16 // 桶数量(LRU-2 使用)
CapPerBucket uint16 // 每桶 L1 容量(LRU-2 使用)
Level2Cap uint16 // 每桶 L2 容量(LRU-2 使用)
CleanupTime time.Duration // 过期清理间隔
OnEvicted func(key string, value store.Value) // 淘汰回调
}
CacheOptions 是创建 Cache 时的配置项,直接映射到 store.Options。 可通过 DefaultCacheOptions() 获取推荐默认值。
func DefaultCacheOptions ¶
func DefaultCacheOptions() CacheOptions
DefaultCacheOptions 返回推荐默认配置:LRU-2、8MB 上限、16 桶、512/256 两级容量、1 分钟清理间隔。
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 是 Peer 接口的 gRPC 实现,封装了到远端缓存节点的连接和 RPC 调用。 通过 grpc.NewClient 建立连接(非阻塞,首次 RPC 时按需建立), 支持 TLS 加密和 Token 认证。
func NewClient ¶
func NewClient(addr string, svcName string, etcdCli *clientv3.Client, opts ...ClientOption) (*Client, error)
NewClient 创建到远端缓存节点的 gRPC 客户端。 若 etcdCli 为 nil 则自动创建一个本地 etcd 客户端。 支持通过 ClientOption 配置 TLS 加密和 Token 认证。
type ClientOption ¶
type ClientOption func(*ClientOptions)
ClientOption 定义客户端配置项
func WithClientAuthToken ¶
func WithClientAuthToken(token string) ClientOption
WithClientAuthToken 配置认证令牌。设置后客户端在每次RPC调用时自动携带该令牌, 以通过服务端的token拦截器校验。测试环境可省略。
func WithClientTLS ¶
func WithClientTLS(caCertFile, serverName string, insecureSkipVerify bool) ClientOption
WithClientTLS 启用TLS连接,可选传入CA证书文件和ServerName。
type ClientOptions ¶
type ClientOptions struct {
TLS bool
CACertFile string // CA证书文件,用于验证服务端身份
ServerName string // 服务端名称(需与证书SAN匹配)
InsecureSkipVerify bool // 跳过服务端证书验证(仅测试环境)
AuthToken string // 节点间认证令牌,非空时通过PerRPCCredentials自动携带
}
ClientOptions 控制 gRPC 客户端的连接行为。
type ClientPicker ¶
type ClientPicker struct {
// contains filtered or unexported fields
}
ClientPicker 是 PeerPicker 的默认实现,整合了一致性哈希路由、gRPC 客户端管理和 etcd 服务发现三大功能。通过 etcd Watch 实时感知集群拓扑变化,动态更新哈希环和连接池。
func NewClientPicker ¶
func NewClientPicker(addr string, opts ...PickerOption) (*ClientPicker, error)
NewClientPicker 创建 ClientPicker 实例。 启动时执行"全量拉取 + Watch 监听"的双阶段服务发现:
- fetchAllServices:一次性获取 etcd 中所有已注册节点
- watchServiceChanges:后台 goroutine 持续监听节点上下线
func (*ClientPicker) Close ¶
func (p *ClientPicker) Close() error
Close 关闭 ClientPicker:取消服务发现 goroutine、关闭所有 Client 连接和 etcd 连接。
type Getter ¶
Getter 定义数据回源加载接口。当缓存未命中且无法从远端节点获取时, 系统调用 Get(ctx, key) 从后端数据源(DB、RPC、文件、计算引擎等)加载数据。 每个 Group 必须配置一个 Getter。
type GetterFunc ¶
GetterFunc 是函数类型适配器,使得普通函数可通过类型转换满足 Getter 接口。 借鉴 http.HandlerFunc 的适配模式:func(ctx, key) ([]byte, error) → Getter。
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group 是 ReachCache 的核心命名空间抽象。每个 Group 代表一个独立的缓存区域, 拥有隔离的存储实例、数据回源回调、过期时间配置和统计信息。
多 Group 解决了不同业务线缓存混放带来的数据混淆、相互干扰和运维困难问题。
核心流程(Get 为例):
Group.Get → 查 mainCache → 命中则返回(localHits++)
→ 未命中 → load() → singleflight.Do → loadData()
→ 有 peers → PickPeer → 远端拉取(peerHits++)
→ 无 peers 或 key 属本节点 → Getter 回调(loaderHits++)
→ 回写 mainCache → 返回
func NewGroup ¶
func NewGroup(name string, cacheBytes int64, getter Getter, opts ...GroupOption) *Group
NewGroup 创建一个 Group 实例并注册到全局表。
必填参数:
- name: 唯一标识,同名 Group 会被覆盖并记录警告
- cacheBytes: 本地缓存的内存上限(字节)
- getter: 数据回源回调,不能为 nil(否则 panic)
可选 opts: WithExpiration / WithPeers / WithCacheOptions
func (*Group) Get ¶
Get 从缓存获取数据,执行三级回源策略:
- 查 mainCache → 命中返回(localHits++)
- load() → singleflight.Do → loadData() a. 有 peers 且 key 属远端 → gRPC 拉取(peerHits++) b. 无 peers 或 key 属本节点 → Getter 回调(loaderHits++)
- 回写 mainCache → 返回
type GroupOption ¶
type GroupOption func(*Group)
GroupOption 是 Group 的配置选项函数类型,实现函数选项模式(Functional Options Pattern)。 优点:新增配置项无需修改 NewGroup 签名;选项函数名即文档;未传入的选项自动使用零值。
func WithCacheOptions ¶
func WithCacheOptions(opts CacheOptions) GroupOption
WithCacheOptions 自定义底层缓存引擎的类型和参数。 可实现不同 Group 使用不同的淘汰策略(如用户 Group 用 LRU、商品 Group 用 LRU-2)。
func WithExpiration ¶
func WithExpiration(d time.Duration) GroupOption
WithExpiration 设置 Group 中缓存项的默认 TTL。0 表示永不过期。
func WithPeers ¶
func WithPeers(peers PeerPicker) GroupOption
WithPeers 注入 PeerPicker 使 Group 具备分布式路由能力。 未设置时 peers 为 nil,Group 运行在单机模式下。
type Peer ¶
type Peer interface {
Get(group string, key string) ([]byte, error)
Set(ctx context.Context, group string, key string, value []byte) error
Delete(ctx context.Context, group string, key string) (bool, error)
Close() error
}
Peer 封装对单个缓存节点的操作能力,使上层可统一操作本地或远程节点。 Client 是 Peer 接口的默认实现(通过 gRPC 通信)。
type PeerPicker ¶
type PeerPicker interface {
// PickPeer 根据 key 选择合适的缓存节点。
// peer: 目标节点的操作接口;ok: 是否存在有效节点;self: 是否为当前节点自身。
PickPeer(key string) (peer Peer, ok bool, self bool)
// Close 关闭节点选择器,释放网络连接等资源。
Close() error
}
PeerPicker 是节点选择器的抽象接口,解耦路由策略与业务逻辑。 给定一个 key,PickPeer 返回应由哪个节点处理、是否找到该节点、是否为本地节点。
type PickerOption ¶
type PickerOption func(*ClientPicker)
PickerOption 是 ClientPicker 的函数选项类型。
func WithClientOptions ¶
func WithClientOptions(opts ...ClientOption) PickerOption
WithClientOptions 为 ClientPicker 设置底层 Client 连接选项(如 WithClientTLS、WithClientAuthToken)。
func WithEtcdEndpointsForClientPicker ¶
func WithEtcdEndpointsForClientPicker(endpoints []string) PickerOption
WithEtcdEndpointsForClientPicker 设置 ClientPicker 使用的 etcd 端点列表。
func WithServiceName ¶
func WithServiceName(name string) PickerOption
WithServiceName 设置 ClientPicker 使用的服务名称(对应 etcd 中的注册前缀)。
type Server ¶
type Server struct {
proto.UnimplementedReachCacheServer // gRPC自动生成的基类,提供接口的默认实现
// contains filtered or unexported fields
}
Server 是 gRPC 缓存服务端,实现了 proto.ReachCacheServer 接口。 负责监听入站 gRPC 连接、解析请求、路由到对应 Group 并返回结果。 Group 查找通过全局注册表 GetGroup(name) 完成,Server 本身不维护独立的 Group 映射。
func NewServer ¶
func NewServer(addr, svcName string, opts ...ServerOption) (*Server, error)
NewServer 创建 gRPC 服务端实例。注册 ReachCache 服务、健康检查服务, 并配置可选的 TLS 加密和 Token 认证拦截器。
func (*Server) Delete ¶
func (s *Server) Delete(ctx context.Context, req *proto.DeleteRequest) (*proto.DeleteResponse, error)
Delete 实现服务端Delete方法
func (*Server) Get ¶
func (s *Server) Get(ctx context.Context, req *proto.GetRequest) (*proto.GetResponse, error)
Get 实现服务端Get方法
func (*Server) Set ¶
func (s *Server) Set(ctx context.Context, req *proto.SetRequest) (*proto.SetResponse, error)
Set 实现服务端Set方法
type ServerOption ¶
type ServerOption func(*ServerOptions)
ServerOption 定义选项函数类型
func WithAdvertiseAddr ¶
func WithAdvertiseAddr(addr string) ServerOption
WithAdvertiseAddr 设置注册到etcd的节点地址(用于其他节点访问)
func WithDialTimeout ¶
func WithDialTimeout(timeout time.Duration) ServerOption
WithDialTimeout 设置连接超时
func WithEtcdEndpoints ¶
func WithEtcdEndpoints(endpoints []string) ServerOption
WithEtcdEndpoints 设置etcd端点
func WithServerAuthToken ¶
func WithServerAuthToken(token string) ServerOption
WithServerAuthToken 配置节点间认证令牌。设置后,gRPC服务端只接受携带相同令牌的客户端连接, 从而阻止非缓存节点的外部程序访问。测试环境可省略此选项。
func WithStatsAddr ¶
func WithStatsAddr(addr string) ServerOption
WithStatsAddr 设置统计接口地址,例如":18001"或"127.0.0.1:18001"
func WithTLS ¶
func WithTLS(certFile, keyFile string) ServerOption
WithTLS 配置服务端TLS证书。若需启用TLS加密通信(推荐生产环境使用),传入PEM格式的证书和密钥文件路径。
type ServerOptions ¶
type ServerOptions struct {
EtcdEndpoints []string // etcd端点
DialTimeout time.Duration // 连接超时
MaxMsgSize int // 最大消息大小
StatsAddr string // 统计接口监听地址,空字符串表示不启用
AdvertiseAddr string // 注册到etcd并供其他节点访问的地址,格式为"ip:port"
TLS bool // 是否启用TLS
CertFile string // 服务端证书文件(PEM格式)
KeyFile string // 服务端密钥文件(PEM格式)
AuthToken string // 节点间认证令牌,为空则不启用认证(仅测试环境)
}
ServerOptions 是 gRPC 服务端的配置项。
Directories
¶
| Path | Synopsis |
|---|---|
|
Package consistenthash 实现了一致性哈希路由算法,支持动态节点增删和自适应负载均衡。
|
Package consistenthash 实现了一致性哈希路由算法,支持动态节点增删和自适应负载均衡。 |
|
examples
|
|
|
sample
command
|
|
|
Package singleflight 提供请求合并(SingleFlight)机制,用于防止缓存击穿。
|
Package singleflight 提供请求合并(SingleFlight)机制,用于防止缓存击穿。 |
|
Package store 是 ReachCache 的本地缓存存储引擎,提供多种淘汰算法的统一接口。
|
Package store 是 ReachCache 的本地缓存存储引擎,提供多种淘汰算法的统一接口。 |
