JAVA使用HBase根据Rowkey批量查询数据(一次查多条,返回多个记录)

最近有需求说是根据多个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();
        }
    }

Hbase表操作

    public static List qurryTableTest(List rowkeyList) throws IOException {
        String tableName = "xxxxx";
        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;
    }

Hbase的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$ < len$; ++i$) {
                    Object o = arr$[i$];
                    results[i++] = (Result)o;
                }
 
                return results;
            } catch (InterruptedException var9) {
                throw (InterruptedIOException)(new InterruptedIOException()).initCause(var9);
            }
        }
    }

实现 多RowKey方式如下:

public static List  queryTableTestBatch(List rowkeyList) throws IOException {
        List getList = 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;
    }

 

你可能感兴趣的:(sboot,hbase)