Java API 讀取HBase表資料
阿新 • • 發佈:2018-11-17
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
方法