【代码随想录知识星球】项目分享-缓存系统(Go)
- 基于 etcd 的服务注册与发现
- 一致性哈希实现负载均衡
- 节点自动发现和同步
- 支持动态扩缩容
- 支持 LRU 缓存策略
- 可配置过期时间
- 支持批量操作
- 防止缓存击穿
- 支持按组划分缓存空间
- 并发安全
- 异步数据同步
- 单飞机制避免缓存击穿
- gRPC 通信
go get github.com/juguagua/lcache
# 使用 Docker 启动 etcd
docker run -d --name etcd \
-p 2379:2379 \
quay.io/coreos/etcd:v3.5.0 \
etcd --advertise-client-urls http://0.0.0.0:2379 \
--listen-client-urls http://0.0.0.0:2379
详情见测试 demo:example/test.go
# 启动节点 A
go run example/test.go -port 8001 -node A
# 启动节点 B
go run example/test.go -port 8002 -node B
# 启动节点 C
go run example/test.go -port 8003 -node C
type ServerOptions struct {
EtcdEndpoints []string // etcd 端点
DialTimeout time.Duration // 连接超时
MaxMsgSize int // 最大消息大小
}
group := lcache.NewGroup("users", 2<<20, getter,
lcache.WithExpiration(time.Hour), // 设置过期时间
)
err := group.Set(ctx, "key", []byte("value"))
value, err := group.Get(ctx, "key")
err := group.Delete(ctx, "key")
- 确保 etcd 服务可用
- 合理配置缓存容量和过期时间
- 节点地址不要重复
- 建议在生产环境配置 TLS
- 使用一致性哈希实现负载均衡
- 异步数据同步减少延迟
- 单飞机制避免缓存击穿
- 支持批量操作提高吞吐量
欢迎提交 Issue 和 Pull Request。
MIT License