先上代码
public static Connection connectToImpala() {
try {
log.info("ketTabPath:" + ketTabPath);
log.info("krb5Path:" + krb5Path);
System.setProperty("java.security.krb5.conf", krb5Path);
System.setProperty("sun.security.krb5.debug", "true");
Configuration conf = new Configuration();
conf.set("hadoop.security.authentication", "kerberos");
UserGroupInformation.setConfiguration(conf);
log.info("设置Hadoop配置以使用Kerberos");
// 使用已登录的用户来建立连接
UserGroupInformation.loginUserFromKeytab("***@METRO.COM",ketTabPath);
log.info("Kerberos用户验证成功");
UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
log.info("loginUser:"+loginUser);
Connection connection = loginUser.doAs(new PrivilegedExceptionAction<Connection>() {
@Override
public Connection run() throws Exception {
String jdbcUrl = "jdbc:impala://<ip>:<port>/<库名>;AuthMech=1;KrbRealm=METRO.COM;KrbHostFQDN=<host>;KrbServiceName=impala";
Class.forName("com.cloudera.impala.jdbc41.Driver");
log.info("准备建立连接");
Connection connection = DriverManager.getConnection(jdbcUrl);
log.info("连接成功:connection:" + connection.getSchema());
return connection;
}
});
return connection;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
遇到的问题:
1.hadoop报错
查看源码可知错误原因conf.set("hadoop.security.authentication", "Kerberos");Kerberos大写改为小写kerberos,这应该是依赖包的问题,当时同事大写是可以的 在我这边不行,我估计不同版本的包这个地方大小写不一样。
2.显示用户错误
kerberos认证成功了,但是去获取connection错误,原因是默认用系统用户进行登录了 所以后来我采用loginUser.doAs这种方式去获取连接,这样表示用已经登陆的用户去获取,这下就没问题啦