在Java中使用Hbase
引入依赖
<!--Hbase客户端和服务端-->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-server</artifactId>
<version>1.3.1</version>
</dependency>
工具类
只涉及查询
public class HbaseUtil {
public static Configuration conf;
private static Connection connection=null;
static {
//配置文件
conf= HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "zookeeper集群地址");
conf.set("hbase.client.ipc.pool.type","RoundRobinPool");
conf.set("hbase.client.ipc.pool.size","8");
//获取连接对象
try {
connection = ConnectionFactory.createConnection(conf);
} catch (IOException e) {
e.printStackTrace();
}
}
//判断表是否存在
public static boolean tableExist(String tabName) throws IOException {
Admin admin = connection.getAdmin();
boolean exists = admin.tableExists(TableName.valueOf(tabName));
//关闭资源
admin.close();
return exists;
}
// 获得连接
public static synchronized Connection getCon() {
if (connection == null || connection.isClosed()) {
try {
connection = ConnectionFactory.createConnection(conf);
} catch (IOException e) {
e.printStackTrace();
}
}
return connection;
}
// 关闭连接
/* public static void close() {
if (connection != null) {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}*/
// 数据读取
//取到一个值
public static String byGet(String tableName, String rowKey, String family,
String qualifier) {
Table table=null;
try {
table= getCon().getTable(TableName.valueOf(tableName));
Get get = new Get(Bytes.toBytes(rowKey));
get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
Result r = table.get(get);
if(r!=null){
if(r.listCells()!=null && r.listCells().size()>0){
table.close();
return Bytes.toString(CellUtil.cloneValue(r.listCells().get(0)));
}
}
table.