HBase根据Rowkey批量查询数据JAVA API(一次查多条,返回多个记录)
最近在生产中遇到了一个需求,前台给我多个rowkey的List,要在hbase中查询多个记录(返回给前台list)。在网上也查了很多,不过自己都不太满意,filter的功能有可能查询结果不是准确值,而网上给出的get方法也都是返回一条,scan的话都是返回全部数据,还有用rowkey范围查询的,都跟我的这个应用场景不符啊。无奈,自己找了一个方法,给各位有同样需求的朋友们一个参考。
首先创建链接属性:
public static Configuration conf = null;
public static Connection connection = null;
public static Admin admin = null;
static {
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "10.120.193.800,10.120.193.810");
conf.set("hbase.master", "10.120.193.730:60010");
conf.set("hbase.zookeeper.property.clientPort", "2181");
conf.set("zookeeper.znode.parent", "/hbase-unsecure");
conf.set("hbase.client.keyvalue.maxsize", "1048576000"); //1G
conf = HBaseConfiguration.create(conf);
try {
connection = ConnectionFactory.createConnection(conf);
admin = connection.getAdmin();
} catch (IOException e) {
e.printStackTrace();
}
}
紧接着,开始做查询操作:
public static List queryTableTest(List rowkeyList) throws IOException {
String tableName = "table_a";
List list = new ArrayList();
Table table = connection.getTable( TableName.valueOf(tableName));// 获取表
for (String rowkey : rowkeyList){
Get get = new Get(Bytes.toBytes(rowkey));
Result result = table.get(get);
for (Cell kv : result.rawCells()) {
String value = Bytes.toString(CellUtil.cloneValue(kv));
list.add(value);
}
}
return list;
}
但是!!!重点来了,每条rowkey都要发起一次请求,这种方法效率十分低,测试了10000条记录查询要用4分钟左右,项目需求是秒回啊,这怎么能行?
于是,就自己点开hbase java 源码,自己慢慢找,忽然眼前一亮!在HTable.class里看到了这个get方法:
public Result[] get(List gets) throws IOException {
if(gets.size() == 1) {
return new Result[]{this.get((Get)gets.get(0))};
} else {
try {
Object[] r1 = this.batch(gets);
Result[] results = new Result[r1.length];
int i = 0;
Object[] arr$ = r1;
int len$ = r1.length;
for(int i$ = 0; i$
这就简单了,紧接着对自己上边的方法进行改进:
public static List queryTableTestBatch(List rowkeyList) throws IOException {
List getList = new ArrayList();
List list = new ArrayList();
String tableName = "table_a";
Table table = connection.getTable( TableName.valueOf(tableName));// 获取表
for (String rowkey : rowkeyList){//把rowkey加到get里,再把get装到list中
Get get = new Get(Bytes.toBytes(rowkey));
getList.add(get);
}
Result[] results = table.get(getList);//重点在这,直接查getList
for (Result result : results){//对返回的结果集进行操作
for (Cell kv : result.rawCells()) {
String value = Bytes.toString(CellUtil.cloneValue(kv));
list.add(value);
}
}
return list;
}
根据这种批量的方法,10000个rowkey进行测试,时间为2s,速度提升特别大。
ok!大功告成,成功解决了问题~
文章评论