《HBase不睡觉书》——客户端API(基础版)

2020-03-05  本文已影响0人  Sky梦启

HBase Maven依赖

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <hbase.version>1.3.5</hbase.version>
    </properties>
<dependencies>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>${hbase.version}</version>
        </dependency>
</dependencies>       

配置文件

Hello HBase

  1. 于加载需要连接HBase的各项配置
    Configuration config = HBaseConfiguration.create();
  2. 添加配置文件
    config.addResource(new Path(ClassLoader.getSystemResource("hbase-site.xml").toURI())); config.addResource(new Path(ClassLoader.getSystemResource("core-site.xml").toURI()));
  3. 创建Connection
    Connection connection = ConnectionFactory.createConnection(config);
  4. 建表
    • 定义表名的TableName
      TableName tableName = TableName.valueOf("mytable");
    • 定义表属性的HTableDescriptor
      HTableDescriptor table = new HTableDescriptor(tablename);
    • 创建列族
      HColumnDescriptor mycf=new HColumnDescriptor("mycf"); table.addFamily(new HColumnDescriptor(mycf));
    • 执行
      Admin admin = connection.qetAdmin(); admin.createTable(table);
    • 结束
      admin.close(); connection.close();
  5. 综上
public class Client {

    public static void main(String[] args) throws URISyntaxException {
        // 获取配置文件
        Configuration conf = HBaseConfiguration.create();
        conf.addResource(new Path(ClassLoader.getSystemResource("hbase-site.xml").toURI()));
        conf.addResource(new Path(ClassLoader.getSystemResource("core-site.xml").toURI()));
        // 创建连接
        try {
            Connection connection = ConnectionFactory.createConnection(conf);
            Admin admin = connection.getAdmin();
            // 定义表名
            TableName tableName = TableName.valueOf("mytable");
            // 定义表
            HTableDescriptor table = new HTableDescriptor(tableName);
            // 定义列族
            HColumnDescriptor mycf = new HColumnDescriptor("mycf");
            table.addFamily(new HColumnDescriptor(mycf));
            // 执行创建表动作
            admin.createTable(table);
            admin.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读