Java连接阿里云HBase示例

使用前要在阿里云的 HBase控制台中点击“修改网络白名单”,然后将你的ip地址(会有提示的)添加到网络白名单中,这样以后才能访问。

所需依赖:

  
    
      com.aliyun.hbase
      alihbase-client
      1.1.1
    
    
        jdk.tools
        jdk.tools
        1.6
        system
        ${JAVA_HOME}/lib/tools.jar
    
  

官方示例代码:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * Created by leibiao on 2017/3/6.
 */
public class HBaseDemo {

    private static final String TABLE_NAME = "mytable";
    private static final String CF_DEFAULT = "cf";
    public static final byte[] QUALIFIER = "col1".getBytes();
    private static final byte[] ROWKEY = "rowkey1".getBytes();

    public static void main(String[] args) {
        Configuration config = HBaseConfiguration.create();
        String zkAddress = "xxxxxxxxx";
        config.set(HConstants.ZOOKEEPER_QUORUM, zkAddress);
        Connection connection = null;

        try {
            connection = ConnectionFactory.createConnection(config);

            HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(TABLE_NAME));
            tableDescriptor.addFamily(new HColumnDescriptor(CF_DEFAULT));
            System.out.print("Creating table. ");
            Admin admin = connection.getAdmin();
            admin.createTable(tableDescriptor);
            System.out.println(" Done.");
            Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
            try {
                Put put = new Put(ROWKEY);
                put.addColumn(CF_DEFAULT.getBytes(), QUALIFIER, "this is value".getBytes());
                table.put(put);
                Get get = new Get(ROWKEY);
                Result r = table.get(get);
                byte[] b = r.getValue(CF_DEFAULT.getBytes(), QUALIFIER);  // returns current version of value
                System.out.println(new String(b));
            } finally {
                if (table != null) table.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

其中 zkAddress 对应 你阿里云 HBase控制台 中 __ZK链接地址(外网地址,需要阿里云发行的客户端。参考文档:https://help.aliyun.com/document_detail/53718.html)__ 对应的那个url链接。

转载于:https://www.cnblogs.com/zifeiy/p/9342100.html

你可能感兴趣的:(Java连接阿里云HBase示例)