Golang学习之路——之tinyrpc源码阅读
tinyrpc是一个高性能的基于protocol buffer
的rpc框架。项目代码非常少,很适合初学者进行golang的学习。
如果你正在为没有资料学习发愁,文末有相关的学习资料获取方式
tinyrpc功能
tinyrpc
基于TCP协议,支持各种压缩格式,基于protocol buffer
的序列化协议。其rpc是基于golang原生的net/rpc
开发而成。
tinyrpc项目结构
tinyrpc
基于net/rpc
开发而成,在此基础上集成了额外的能力。项目结构如图:
功能目录如下:
- codec 编码模块
- compressor 压缩模块
- header 请求/响应头模块
- protoc-gen-tinyrpc 代码生成插件
- serializer 序列化模块
tinyrpc源码解读
客户端和服务端构建
客户端是以net/rpc
的rpc.Client
为基础构建,在此基础上定义了Option
以配置压缩方式和序列化方式:
type Option func(o *options)
type options struct {
compressType compressor.CompressType
serializer serializer.Serializer
}
在创建客户端的时候将配置好的压缩算法和序列化方式作为创建客户端的参数:
func NewClient(conn io.ReadWriteCloser, opts ...Option) *Client {
options := options{
compressType: compressor.Raw,
serializer: serializer.Proto,
}
for _, option := range opts {
option(&options)
}
return &Client{rpc.NewClientWithCodec(
codec.NewClientCodec(conn, options.compressType, options.serializer))}
}
服务端是以net/rpc
的rpc.Server
为基础构建,在此基础上扩展了Server
的定义:
type Server struct {
*rpc.Server
serializer.Serializer
}
在创建客户端和开启服务时传入序列化方式:
func NewServer(opts ...Option) *Server {
options := options{
serializer: serializer.Proto,
}
for _, option := range opts {
option(&options)
}
return &Server{&rpc.Server{}, options.serializer}
}
func (s *Server) Serve(lis net.Listener) {
log.Printf("tinyrpc started on: %s", lis.Addr().String())
for {
conn, err := lis.Accept()
if err != nil {
continue
}
go s.Server.ServeCodec(codec.NewServerCodec(conn, s.Serializer))
}
}
压缩算法compressor
压缩算法的实现中首先是定义了压缩的接口:
type Compressor interface {
Zip([]byte) ([]byte, error)
Unzip([]byte) ([]byte, error)
}
压缩的接口包含压缩和解压方法。
压缩算法使用的是uint
类型,使用iota
来初始化,并且使用map来进行所有压缩算法实现的管理:
type CompressType uint16
const (
Raw CompressType = iota
Gzip
Snappy
Zlib
)
// Compressors which supported by rpc
var Compressors = map[CompressType]Compressor{
Raw: RawCompressor{},
Gzip: GzipCompressor{},
Snappy: SnappyCompressor{},
Zlib: ZlibCompr
还没有评论,来说两句吧...