zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

hbase 存储乱码的问题--解决方案

HBase存储解决方案 -- 乱码 问题
2023-09-27 14:22:12 时间

最近在将一些数字型的数据转成字节后存储到hbase中,出现了乱码问题,如下:

    public byte[] nextId() {
        try {
            long partitionId = currentId % partition;
            return Bytes.add(Bytes.toBytes(partitionId),
                    Bytes.toBytes(currentId));
        } finally {
            currentId++;
        }
    }
 public static void main(String args[])throws  Exception{
        ModPartitionRowKeyManager rkManager = new ModPartitionRowKeyManager();
        //只预建10个分区
        rkManager.setPartition(10);
        byte [][] splitKeys = rkManager.calcSplitKeys();
        //插入1亿条记录,看数据分布
        for(int i = 0; i < 100; i ++) {
            String s = new String(rkManager.nextId());//rkManager.nextId();
            System.out.println("s:"+s);
        }
}

解决办法:需要先将 int, double 型数据转换成 String 类型,此时即可正常显示

从中可以看出,直接把 int 型的参数传入 Bytes.toBytes() 函数中,编译不会报错,但数据的格式发生错误,再显示时就会出现乱码,因此,在调用 Bytes.toBytes() 函数时,需要先将 int, double 型数据转换成 String 类型,此时即可正常显示。

查看结果:

查询hbase数据库中的数据:

    public static void main(String args[])throws  Exception{
        Table table=    HbaseConnectionUtils.getInstance().getTable("hash_split_table2");
        scanRecord2(table);
    }
    /**
     * scan 全量查询
     * @param hTable
     * @throws IOException
     */
    private static void scanRecord2(Table hTable) throws IOException {
        Scan scan = new Scan();
        ResultScanner scanner = hTable.getScanner(scan);
        int count=1;
        for (Result result : scanner) {
            System.out.println("rowKey:"+new String(Bytes.toString(result.getRow())));
            for (Cell cell : result.rawCells()) {
                String v =new String(CellUtil.cloneQualifier(cell));
                // System.out.println("v"+v);

                if(v.equals("register_time")){
                    System.out.println(count+"列族:"+new String(CellUtil.cloneFamily(cell))+ " 列:"+new String(CellUtil.cloneQualifier(cell))+ " 值:"+new String(CellUtil.cloneValue(cell)));
                    count++;
                }
            }
        }
    }
部分截图:
rowKey:99909
rowKey:99919
rowKey:99929
rowKey:99939
rowKey:99949
rowKey:99959
rowKey:99969
rowKey:99979
rowKey:99989
rowKey:9999
rowKey:99999

ok!乱码问题解决!!