需求说明
如果要本地调试Hbase程序,那么可以用本地连接集群的方式
配置文件
在maven里,配置文件cluster.properties放在target/classes里
cluster.properties的内容如下:
hbase.address=hadoop1,hadoop2,....
读取配置文件代码:
import java.io.IOException;
import java.util.Properties;
public class ClusterConfigUtil {
private static Properties prop = null;
static{
prop = new Properties();
try {
prop.load(ClusterConfigUtil.class.getResourceAsStream("/cluster.properties"));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
public static String getValue(String name){
String value = prop.getProperty(name);
return value;
}
}
创建hbase配置信息:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import java.io.IOException;
public class HBaseUtil {
private static HConnection hconn = null;
public static HConnection getConnection() throws IOException{
if(hconn == null || hconn.isClosed()){
Configuration conf = HBaseConfiguration.create();// 创建配置信息
conf.set("hbase.zookeeper.quorum", ClusterConfigUtil.getValue("hbase.address"));// zookeeper的ip
conf.set("hbase.zookeeper.property.clientPort", "2181");// zookeeper的端口
hconn = HConnectionManager.createConnection(conf);
}
return hconn;
}
}
用如下方式调用:
HConnection connection = HBaseUtil.getConnection();
Configuration conf = connection.getConfiguration();