上一篇介绍了HBase的基本概念,以及其在linux环境下的安装和交互,本文将继续介绍如何通过java和python来操作hbase。
在通过api操作hbase之前,首先要保证hadoop和hbase已经都启动了。
Java操作HBase
创建一个maven项目,添加基本的依赖:
<properties>
<hadoop.version>2.10.0</hadoop.version>
<hbase.version>1.3.6</hbase.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>${hbase.version}</version>
</dependency>
</dependencies>
通过java api创建表User,并列出所有的表,demo如下:
package cn.howe;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import java.io.IOException;
public class HtableTest {
//配置类
public static Configuration configuration ;
// 连接类
public static Connection connection ;
// 管理类
public static Admin admin;
public static void init() {
configuration = HBaseConfiguration.create();
configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase");
try {
connection = ConnectionFactory.createConnection(configuration);
admin = connection.getAdmin();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
init(); // 初始化
createTable("User", new String[]{"info"});
listTable();
}
public static void listTable() throws Exception {
System.out.println("**********table:*******");
TableName[] tableNames = admin.listTableNames();
for (TableName tableName : tableNames) {
System.out.println(tableName);
}
}
public static void createTable(String tabName, String[] colFamily) throws IOException {
TableName tableName = TableName.valueOf(tabName);
if(admin.tableExists(tableName)) {
System.out.println("table exists: " + tabName);
} else {
HTableDescriptor desc = new HTableDescriptor(tableName);
// 创建列族
for (String family : colFamily) {
HColumnDescriptor fal = new HColumnDescriptor(family);
desc.addFamily(fal);
}
admin.createTable(desc);
System.out.println("Table create successful!");
}
}
}
可以通过命令行查看真的创建成功:
来源:CSDN
作者:还是转转
链接:https://blog.csdn.net/xiaoyi52/article/details/103738691