java client api 访问hbase
public class HbaseUtil implements Serializable {
public static String getValue(Connection connection, String tableName, String rowKey, String columnFamilyName, String column) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Get get = new Get(Bytes.toBytes(rowKey));
Result result = table.get(get);
return Bytes.toString(result.getValue(Bytes.toBytes(columnFamilyName), Bytes.toBytes(column)));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static byte[] getRow(Connection connection, String tableName, String rowKey) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Get get = new Get(Bytes.toBytes(rowKey));
byte[] row = table.get(get).getRow();
return row;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static boolean putRow(Connection connection, String tableName, String rowKey, String columnFamilyName, List<Pair<String, String>> pairList) {
try {
Table table = connection.getTable(TableName.valueOf(tableName));
Put put = new Put(Bytes.toBytes(rowKey));
pairList.forEach(pair -> put.addColumn(Bytes.toBytes(columnFamilyName), Bytes.toBytes(pair.getKey()), Bytes.toBytes(pair.getValue())));
table.put(put);
table.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public static Connection conn(String zkAddress, String userName, String password) {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", zkAddress);
conf.set("hbase.client.username", userName);
conf.set("hbase.client.password", password);
conf.set("hbase.client.connection.impl", AliHBaseUEClusterConnection.class.getName());
Connection connection = null;
try {
connection = ConnectionFactory.createConnection(conf);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}