实验环境
Hadoop2.8.0
Hbase-1.4.9
Centos7.2
Java代码
package pers.haohan.bigdata.hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
public class TestHbaseAPI_1 {
public static void main(String[] args) throws IOException {
Configuration conf = HBaseConfiguration.create();
Connection connection = ConnectionFactory.createConnection(conf);
System.out.println(connection);
Admin admin = connection.getAdmin();
try {
NamespaceDescriptor namespace = admin.getNamespaceDescriptor("test");
} catch (NamespaceNotFoundException e) {
NamespaceDescriptor nd = NamespaceDescriptor.create("test").build();
admin.createNamespace(nd);
}
TableName tableName = TableName.valueOf("test:student");
boolean flg = admin.tableExists(tableName);
System.out.println(flg);
if (flg) {
Table table = connection.getTable(tableName);
String rowkey = "1001";
Get get = new Get(Bytes.toBytes(rowkey));
Result result = table.get(get);
boolean empty = result.isEmpty();
System.out.println("1001数据是否存在 = " + !empty);
if (empty) {
Put put = new Put(Bytes.toBytes(rowkey));
String family = "info";
String column = "name";
String val = "zhangsan";
put.addColumn(Bytes.toBytes(family), Bytes.toBytes(column), Bytes.toBytes(val));
table.put(put);
System.out.println("增加数据");
} else {
for (Cell cell : result.rawCells()) {
System.out.println("value = " + Bytes.toString(CellUtil.cloneValue(cell)));
System.out.println("raw = " + Bytes.toString(CellUtil.cloneRow(cell)));
System.out.println("family = " + Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println("column = " + Bytes.toString(CellUtil.cloneQualifier(cell)));
}
}
} else {
HTableDescriptor td = new HTableDescriptor(tableName);
HColumnDescriptor cd = new HColumnDescriptor("info");
td.addFamily(cd);
admin.createTable(td);
System.out.println("表格创建成功");
}
}
}
XML文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pers.haohan.bigdata</groupId>
<artifactId>hbasestudy</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>hbase_mr</module>
</modules>
<dependencies>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-server</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
</project>