Golang通过thrift连接Hive简单demo

DJZhu · · 1003 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

网上关于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
}


有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:DJZhu

查看原文:Golang通过thrift连接Hive简单demo

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077

1003 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传