HbaseConnKer.java
package BigData.conn; import BigData.utils.resource.ResourcesUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.security.UserGroupInformation; import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties; public class HbaseConnKer { private static Connection connectionKer = null; private static volatile HbaseConnKer instanceKer; private HbaseConnKer() {
try {
Properties pro = ResourcesUtils.getResourceAsProperties("Kerberos/HbaseConfigKer.properties"); /* 这个配置文件主要是记录 kerberos的相关配置信息,例如KDC是哪个IP?默认的realm是哪个?
这个文件是从远程服务器上copy下来的*/
System.setProperty("java.security.krb5.conf", pro.getProperty("java.security.krb5.conf")); Configuration conf = HBaseConfiguration.create(); // -----Kerberos配置-----
InputStream hbaseSiteInputStream = Files.newInputStream(Paths.get(pro.getProperty("hbase.site")));
if (hbaseSiteInputStream == null) {
System.out.println("The hbase-site.xml is null!");
}
conf.addResource(hbaseSiteInputStream);
conf.set("hadoop.security.authentication", pro.getProperty("hadoop.security.authentication")); // 这个可以理解成用户名信息,也就是Principal
conf.set("kerberos.principal", pro.getProperty("kerberos.principal")); UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab(pro.getProperty("kerberos.principal"),
pro.getProperty("kerberos.keytab"));
// ---------- //显示连接的服务器
System.out.println("连接服务器:"+conf.get("hbase.zookeeper.quorum")); connectionKer = ConnectionFactory.createConnection(conf);
System.out.println("创建connection成功!");
} catch (IOException e) {
e.printStackTrace();
} } public static Connection getConnection() {
return connectionKer;
} public static HbaseConnKer getIstance() {
// 定义一个共有的静态方法,返回该类型实例
if (instanceKer == null) {
// 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率)
synchronized (HbaseConnKer.class) {
// 同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
if (instanceKer == null) {
// 未初始化,则初始instance变量
instanceKer = new HbaseConnKer();
}
}
}
return instanceKer;
}
}
HbaseConfigKer.properties
# HBase config
hbase.zookeeper.quorum=20.1.1.93
hbase.zookeeper.property.clientPort=2181 java.security.krb5.conf=src/main/resources/Kerberos/krb5.conf
hadoop.security.authentication=kerberos
hbase.site=src/main/resources/Kerberos/hbase-site.xml
kerberos.keytab=src/main/resources/Kerberos/XXX.keytab
kerberos.principal=XXX@XX.COM