java 操作 hbase

数据存储

2018-09-24

277

0

技术:hbase + java8

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:提供一个java 操作hbase基础操作封装

1. maven依赖


    org.apache.hbase
    hbase-client
    1.0.0

2. 添加zk配置 

private static Configuration conf = null;

static {
    conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "asxasasx:2181/hbase");
}

3. 添加操作方法(操作api)

 

public static boolean creatTable(String tableName, List families) throws Exception {
        TableName tn = TableName.valueOf(tableName);
        try (Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(tn);) {
            HTableDescriptor tableDescriptor = new HTableDescriptor(tn);
            for (int i = 0; i <= families.size() - 1; i++) {
                tableDescriptor.addFamily(new HColumnDescriptor(families.get(i)));
            }
            Admin admin = connection.getAdmin();
            if (!admin.tableExists(tn)) {
                admin.createTable(tableDescriptor);
                System.out.println(tableName + " created");
                return true;
            }
        }
        return false;
    }

4. 添加数据,查询数据

 public static void put(String tableName, String rowKey, String familyName, String columnName, String value) throws Exception {
        HTable htable = new HTable(conf, Bytes.toBytes(tableName));
        Put put = new Put(Bytes.toBytes(rowKey));
        put.add(Bytes.toBytes(familyName), Bytes.toBytes(columnName), Bytes.toBytes(value));
        htable.put(put);
    }

    public static Result getResult(String tableName, String rowKey) throws Exception {
        Get get = new Get(Bytes.toBytes(rowKey));
        HTable htable = new HTable(conf, Bytes.toBytes(tableName));
        Result result = htable.get(get);
        return result;
    }

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think