Java API 读取HBase表数据
1.
在使用java api 去获取数据的时候,先用 hbase shell
展示一下 hbase 中的表。
hbase(main):005:0> scan 'tsdb-uid'
ROW COLUMN+CELL
\x00 column=id:metrics, timestamp=1541500656882, value=\x00\x00\x00\x00\x00\x00\x00\x05
\x00 column=id:tagk, timestamp=1535982247222, value=\x00\x00\x00\x00\x00
···
\x00\x00\x08 column=name:tagv, timestamp=1541425665725, value=firminal
Firminal column=id:tagv, timestamp=1537103490289, value=\x00\x00\x06
accessNumber column=id:tagk, timestamp=1535982247235, value=\x00\x00\x03
chl column=id:tagk, timestamp=1535891521203, value=\x00\x00\x02
cs column=id:tagv, timestamp=1535982247259, value=\x00x00\x05
···
25 row(s) in 0.0770 seconds
hbase(main):007:0> get 'tsdb-uid','cs'
COLUMN CELL
id:tagv timestamp=1535982247259, value=\x00\x00\x05
1 row(s) in 0.0240 seconds
通过观察 tsdb-uid
表,可以看到有一个 rowKey = cs
,且其值为(hex)000005
,那么使用java api去获取数据的代码如下:
2. 使用Java获取HBase的数据
2.1 get
方法
- 静态变量
public static Configuration conf ;
private static Connection connection;
private static Admin admin;
//step2:you should set some properties
//connection should be closed,but not
static{
System.out.println("Hello,static code is started...");
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "192.168.211.4");
conf.set("hbase.zookeeper.property.clientPort", "2181");
try {
connection= ConnectionFactory.createConnection(conf);
} catch (IOException e) {
e.printStackTrace();
}
//new way to get an HBaseAdmin
try {
admin = connection.getAdmin();
} catch (IOException e) {
e.printStackTrace();
}
}
- get的使用
public static void getRowFromTable(String tableName,String qualifier){
try {
Table table = connection.getTable(TableName.valueOf(tableName));
byte[] row = new byte[]{};
row = qualifier.getBytes();
Get g = new Get(row);
// Reading the data
Result result = table.get(g);
// Reading values from Result class object
byte [] value1 = result.getValue(Bytes.toBytes("id"),Bytes.toBytes("tagv"));
byte [] value2 = result.getValue(Bytes.toBytes("id"),Bytes.toBytes("timestamp"));
for(int i = 0;i< value1.length;i++){
System.out.print(value1[i]);
}
CustomedMethod.printDelimiter();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
System.setProperty("hadoop.home.dir", "D:\\SoftWarePackages\\BigData\\hadoop-2.6.4");
HBaseUtils.getRowFromTable("tsdb-uid","cs");
HBaseUtils.closeAll();
} catch (IOException e) {
e.printStackTrace();
}
}
得到的结果如下:
2.2 scan
方法