考虑到Java代码一般就是查询hbase存储的hadoop运算的结果数据,下面记录下查询的简单范例代码
package com.lvmama.crm.web.controller.csVipManager;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
/**
* Created by zoubin on 2017-5-22.
*/
public class HbaseTest {
private Configuration configuration;
@Before
public void setUp(){
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "node3,node4,node5");//通过zookeeper关联上hbase
}
/**
* 根据rowkey查找数据
* @throws IOException
*/
@Test
public void getResult() throws IOException {
Get get = new Get(Bytes.toBytes("row1"));
HTable table = new HTable(configuration,Bytes.toBytes("test"));
Result result = table.get(get);
for(KeyValue keyValue: result.list()){
System.out.println("family :" + Bytes.toString(keyValue.getFamily()));//列簇名
System.out.println("qualifier :"+ Bytes.toString(keyValue.getQualifier()));//列名
System.out.println("value :"+Bytes.toString(keyValue.getValue()));//列对应的值
System.out.println("timestamp :" +keyValue.getTimestamp());//数据最后更新时间
System.out.println("---------------------------------");
}
}
/**
* 查询指定rowkey范围的数据
* @throws IOException
*/
@Test
public void getResults() throws IOException {
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes("row2"));
scan.setStopRow(Bytes.toBytes("row4"));//实验发现范围取[row2,row4),左闭右开
ResultScanner rs = null;
HTable table = new HTable(configuration, Bytes.toBytes("test"));
rs = table.getScanner(scan);
for(Result r : rs){
for (KeyValue kv : r.list()){
System.out.println("row:" + Bytes.toString(kv.getRow()));
System.out.println("family:"+ Bytes.toString(kv.getFamily()));
System.out.println("qualifier:"+ Bytes.toString(kv.getQualifier()));
System.out.println("value:" + Bytes.toString(kv.getValue()));
System.out.println("timestamp:" + kv.getTimestamp());
System.out.println("-------------------------------------------");
}
}
}
}