java: 写入数据到HBase

一、添加依赖

        
            org.apache.hadoop
            hadoop-client
            2.6.0
        

        
            org.apache.hbase
            hbase-client
            2.4.2
        

二、调用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);
        }
    }
}

java: 写入数据到HBase_第1张图片

你可能感兴趣的:(Hadoop,java,hbase,开发语言)