首先编写thrift文件(rpcserver.thrift),运行thrift --gen go rpcserver.thrift,生成代码
namespace go rpc service RpcService { string SayHi(1: string name); void SayHello(string name); }
搭建一个以二进制为传输协议的服务器如下:
type rpcService struct{ } func (this *rpcService)SayHi(name string)(r string,err error){ fmt.Println("Hi ",name) r = Hello "+name err = nil return } func (this *rpcService)SayHello(name string)err error{ fmt.Println( nil return } func StartServer(){ serverTransport,err := thrift.NewTServerSocket(127.0.0.1:8808") if err != nil { fmt.Println(Error!return } handler := &rpcService{} processor := NewRpcServiceProcessor(handler) server := thrift.NewTSimpleServer2(processor,serverTransport) fmt.Println(thrift server in localhost") server.Serve() }
查看自动生成的代码recserver.go,我们发现NewRpcServiceProcessor函数代码如下:
func NewRpcServiceProcessor(handler RpcService) *RpcServiceProcessor { self4 := &RpcServiceProcessor{handler: handler,processorMap: make(map[string]thrift.TProcessorFunction)} self4.processorMap[SayHi"] = &rpcServiceProcessorSayHi{handler: handler} self4.processorMap[SayHello"] = &rpcServiceProcessorSayHello{handler: handler} return self4 }