专注于
IT技术和业内交流

go thrift 中间件

首先是服务器端的thrift RPC操作
package server

import (
“git.apache.org/thrift.git/lib/go/thrift”
“net”
“time”
)

//多服务服务端
type MultiServer struct{
ListenHost string
ListenPort string
TimeOut int

ServerSocket     *thrift.TServerSocket
TransportFactory thrift.TTransportFactory
protocolFactory  *thrift.TBinaryProtocolFactory
Processor        *thrift.TMultiplexedProcessor
Server           *thrift.TSimpleServer

}

//单个服务处理
type ServerProcessor struct{
ServaerName string
Processor thrift.TProcessor
}

func NewMultiServer(host, port string, timeout int) (ret *MultiServer, err error) {
ret = &MultiServer{ListenHost: host, ListenPort: port, TimeOut: timeout}

ret.ServerSocket, err = thrift.NewTServerSocketTimeout(net.JoinHostPort(ret.ListenHost, ret.ListenPort), time.Duration(ret.TimeOut)*time.Second)
iferr != nil {
    returnnil, err
}

ret.TransportFactory = thrift.NewTTransportFactory()
ret.TransportFactory = thrift.NewTFramedTransportFactory(ret.TransportFactory)
ret.protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
ret.Processor = thrift.NewTMultiplexedProcessor()
ret.Server = thrift.NewTSimpleServer4(ret.Processor, ret.ServerSocket, ret.TransportFactory, ret.protocolFactory)

returnret, nil

}

客户端go语言通过thrift 发起rpc请求
package client

import (
“git.apache.org/thrift.git/lib/go/thrift”
“net”
“time”
)

var (
transportFactory thrift.TTransportFactory = thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
protocolFactory *thrift.TBinaryProtocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
)

//链接提供多种服务的客户端个体,需要指定其服务名称来选择对应的服务
type ThriftClient struct{
host string //服务器ip
port string //服务器端口
timeOut int //等待服务反应的超时时间
ServerName string //服务名称

socket    *thrift.TSocket          //与服务器的链接
transport *thrift.TFramedTransport //thrift运输框架
protocol  thrift.TProtocol         //thrift远程代理
Client    interface{}              //具体用来操作的客户端结构,结构由客户端和服务器端所共同用的thrift文件中服务结构决定

}

//初始化客户端结构,对所有面对提供多服务的客户端结构都合适
func NewthriftClient(host, port, name string, timeout int) (ret ThriftClient, err error) {
ret = &ThriftClient{host: host, port: port, timeOut: timeout, ServerName: name}
ret.socket, err = thrift.NewTSocketTimeout(net.JoinHostPort(host, port), time.Duration(ret.timeOut)
time.Second)
iferr != nil {
returnnil, err
}
ret.transport = thrift.NewTFramedTransport(ret.socket)
ret.protocol = thrift.NewTBinaryProtocolTransport(ret.transport)
ret.protocol = thrift.NewTMultiplexedProtocol(ret.protocol, ret.ServerName)
returnret, nil
}

未经允许,不得转载本站任何文章:代码山 » go thrift 中间件

分享到:更多 ()

专注品牌化高端网站建设

商务服务联系我们