# 接上文,本文讲解 thrift
1. 下载网址
https://thrift.apache.org/
2. 编写thrift文件
thrift --gen <language> <Thrift filename>
namespace go thrift
struct EchoReq {
1: string msg; //参数1
2: string name; //参数2
}
struct EchoRes {
1: string msg;
2: string name;
}
service Echo {
EchoRes echo(1: EchoReq req)
}
生成的core文件在test.go中
3. 编写client.go、server.go
__________________________________________________________________client.go
package main
import (
"context"
"fmt"
"github.com/apache/thrift/lib/go/thrift"
"log"
"net"
"os"
thrift2 "test/thrift_test/gen-go/thrift"
)
func main() {
transportFactory := thrift.NewTBufferedTransportFactory(8192)
protocolFactory := thrift.NewTCompactProtocolFactory()
transport,err := thrift.NewTSocket(net.JoinHostPort("127.0.0.1","9898"))
if err != nil {
fmt.Fprintln(os.Stderr,"error resolving address:, ",err)
os.Exit(1)
}
userTransport,err := transportFactory.GetTransport(transport)
client := thrift2.NewEchoClientFactory(userTransport,protocolFactory) //调用test中的core函数
if err := transport.Open();err != nil {
fmt.Fprintln(os.Stderr,"error opening socket to 127.0.0.1:9898:, ",err)
os.Exit(1)
}
defer transport.Close()
req := thrift2.EchoReq{Msg:"hello boy!",Name:"lxy"}
res,err := client.Echo(context.Background(),&req) // 调用 server与client 约定的 echo 服务
if err != nil {
log.Println("echo failed ",err)
return
}
log.Println("response: ",req.Msg + " " + res.Name)
fmt.Println("well done! ")
return
}
__________________________________________________________________server.go
package main
import (
"context"
"fmt"
"github.com/apache/thrift/lib/go/thrift"
thrift2 "test/thrift_test/gen-go/thrift"
)
type TestServer struct {
}
// server与client 约定的 call 函数
func (e *TestServer) Echo(ctx context.Context,req *thrift2.EchoReq) (*thrift2.EchoRes,error) {
fmt.Println("Message from client: ",req.GetMsg())
res := &thrift2.EchoRes{
Msg:"success",
}
return res,nil
}
func main() {
transport,err := thrift.NewTServerSocket(":9898")
if err != nil {
panic(err)
}
handler := &TestServer{}
processor := thrift2.NewEchoProcessor(handler)
transportFactory := thrift.NewTBufferedTransportFactory(8192)
protocolFactory := thrift.NewTCompactProtocolFactory()
server := thrift.NewTSimpleServer4(processor,transport,transportFactory,protocolFactory,)
if err := server.Serve(); err != nil {
panic(err)
}
return
}