java: 写入数据到HBase

发布时间:2024年01月05日

一、添加依赖

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.6.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>2.4.2</version>
        </dependency>

二、调用API写HBase示例

package cn.edu.tju;

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class TestHbaseWrite {
    public static void main(String[] args) throws Exception{
        Configuration config = HBaseConfiguration.create();// create configuration
        //zookeeper 地址
        config.set("hbase.zookeeper.quorum","xxx.xxx.xxx.xxx");//
        //zookeeper端口
        config.set("hbase.zookeeper.property.clientPort", "2181");//
        //表名,必须提前在hbase中创建
        String tableName ="c1";
        //row key
        String rowKey = "myRowKeyTest";
        //family,必须是hbase中有的family
        String familyName = "fam3";
        //column
        String columnName = "age";
        //value
        String columnValue = "18";
        Connection connection = ConnectionFactory.createConnection(config);
        Table table = null;
        try {
            table = connection.getTable(TableName.valueOf(tableName));
            Put put = new Put(Bytes.toBytes(rowKey));
            put.addColumn(familyName.getBytes(), Bytes.toBytes(columnName),Bytes.toBytes(columnValue));
            table.put(put);
        }
        catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
        finally {
            IOUtils.closeQuietly(table);
        }
    }
}

在这里插入图片描述

文章来源:https://blog.csdn.net/amadeus_liu2/article/details/135412352
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。