Golang通过thrift连接Hive简单demo
博客专区 > DJZhu 的博客 > 博客详情
Golang通过thrift连接Hive简单demo
DJZhu 发表于1个月前
Golang通过thrift连接Hive简单demo
  • 发表于 1个月前
  • 阅读 13
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 十分钟定制你的第一个小程序>>>   

网上关于golang操作hive的文章很少, 最近在用, 研究的过程中记一点代码片段.

package my_hive_cli

import (
	"..../hive/tcliservice"
	"git.apache.org/thrift.git/lib/go/thrift"
)

func NewClient(host string, username string, password string, dbname string) (*tcliservice.TCLIServiceClient, error) {
	transport, err := thrift.NewTSocket(host)
	if err != nil {
		return nil, err
	}
	if err := transport.Open(); err != nil {
		return nil, err
	}
	protocol := thrift.NewTBinaryProtocolFactoryDefault()
	client := tcliservice.NewTCLIServiceClientFactory(transport, protocol)

	openSessionReq := tcliservice.NewTOpenSessionReq()
	if username != "" {
		openSessionReq.Username = &username
		openSessionReq.Password = &password
	}
	openSessionReq.ClientProtocol = tcliservice.TProtocolVersion_HIVE_CLI_SERVICE_PROTOCOL_V5
	if dbname != "" {
		if openSessionReq.Configuration == nil {
			openSessionReq.Configuration = make(map[string]string)
		}
		openSessionReq.Configuration["use:"] = dbname
	}
	openSessionResp, err := client.OpenSession(openSessionReq)
	if err != nil {
		return nil, err
	}
	sessionHandler := openSessionResp.GetSessionHandle()

	exeReq := tcliservice.NewTExecuteStatementReq()
	exeReq.SessionHandle = sessionHandler
	exeReq.Statement = "SELECT COUNT(1) FROM default.test"
	exeResp, err := client.ExecuteStatement(exeReq)
	if err != nil {
		return nil, err
	}
	operationHandler := exeResp.GetOperationHandle()

	fetchReq := tcliservice.NewTFetchResultsReq()
	fetchReq.OperationHandle = operationHandler
	fetchReq.Orientation = tcliservice.TFetchOrientation_FETCH_FIRST
	fetchReq.MaxRows = 10
	fetchResp, err := client.FetchResults(fetchReq)
	if err != nil {
		return nil, err
	}
	res := fetchResp.GetResults().GetRows()
	for _,r := range res{
		row := r.GetColVals()
		for _, filed := range row {
			if filed.IsSetI64Val() {
				println("i64", filed.GetI64Val().GetValue())
			}
			if filed.IsSetI32Val() {
				println("i32", filed.GetI32Val().GetValue())
			}
		}
	}

	closeOperationReq := tcliservice.NewTCloseOperationReq()
	closeOperationReq.OperationHandle = operationHandler
	client.CloseOperation(closeOperationReq)
	closeSessionReq := tcliservice.NewTCloseSessionReq()
	closeSessionReq.SessionHandle = sessionHandler
	client.CloseSession(closeSessionReq)

	transport.Close()

	return client, nil
}

标签: hive Thrift Go
共有 人打赏支持
粉丝 3
博文 25
码字总数 29881
×
DJZhu
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: