在应用Hive之前,首先搭建Hive环境,关于Hive的搭建 参考之前的搭建文档

java代码执行Hive脚本

java代码执行Hive脚本,需要启动Hive的内部服务,供其他或者java代码链接,Hive内部服务启动命令

# ./hive --service hiveserver2

0818b9ca8b590ca3270a3433284dd417.png

启动成功后tcp会自动监听 一个10000的端口

0818b9ca8b590ca3270a3433284dd417.png

但是这里监听的IP是127.0.0.1,是不能供其它链接的,需要修改配置文件,指定服务地址,IP或者服务器名称

需改 Hive-site.xml 的配置文件

# vi ../conf/hive-site.xml

需要把如下value的localhost 改为服务器名称或者IP

hive.server2.thrift.bind.host

centos-node6

Bind host on which to run the HiveServer2 Thrift interface.

Can be overridden by setting $HIVE_SERVER2_THRIFT_BIND_HOST

再次启动Hive的内部服务,查看监听的tcp和端口号服务

0818b9ca8b590ca3270a3433284dd417.png

内部服务开启成功,现在可以供其它链接Hive,本地测试 命令进入/bin目录下

# ./beeline

beeline> !connect jdbc:hive2://centos-node6/default;

0818b9ca8b590ca3270a3433284dd417.png

用户名默认:root 密码:无

登陆成功后命令查看default数据库中的表

show tables

出现错误 5000L,这是Hive的一个bug,需要修改配置文件

0818b9ca8b590ca3270a3433284dd417.png

修改配置文件 hive-site.xml,修改value值为5000

hive.server2.long.polling.timeout

5000

Time in milliseconds that HiveServer2 will wait, before responding to asynchronous calls that use long polling

再次命令查看default 中的表 show tables

0818b9ca8b590ca3270a3433284dd417.png

远程链接Hive测试成功!

java代码JDBC链接Hive

jdbc测试链接Hive代码如下

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

/** * Hive远程测试连接 *@author llh * */

public class HiveTest {

public static void main(String[] args) throws Exception{

Class.forName("org.apache.hive.jdbc.HiveDriver");

Connection conn = DriverManager.getConnection("jdbc:hive2://centos-node6/default", "root", "");

try {

Statement st = conn.createStatement();

ResultSet re = st.executeQuery("select count(*) from t_emp");

if(re.next()){

System.err.println("t_emp数据条数:"+re.getInt(1));

}

} catch (Exception e) {

e.printStackTrace();

}finally{

conn.close();

}

}

}

0818b9ca8b590ca3270a3433284dd417.png

测试成功

Logo

一站式 AI 云服务平台

更多推荐