一.JavaAPI:
1 新建Maven Project
新建项目后在pom.xml中添加依赖:
pom.xml
org.apache.hbase
hbase-server
1.3.1
org.apache.hbase
hbase-client
1.3.1
org.apache.hbase
hbase-common
1.3.1
2 编写常用HBaseAPI
注意:这是学习使用的老版本的API,
(0)若想要在控制台打印关于hbase的日志,需要将目录/opt/module/hbase-1.3.1/conf中的log4j.properties拷贝到resources目录中:
(1). 首先需要获取Configuration对象:
public static Configuration conf;
static{
//使用HBaseConfiguration的单例方法实例化
conf = HBaseConfiguration.create();
//连接的集群,ZK的端口号,连接ZK的节点
conf.set("hbase.zookeeper.quorum", "hadoop1");
conf.set("hbase.zookeeper.property.clientPort", "2181");
conf.set("zookeeper.znode.parent", "/hbase");
}
(2).判断表是否存在:
public static boolean isTableExist(String tableName) throws Exception{
//在HBase中管理、访问表需要先创建HBaseAdmin对象
Connection connection = ConnectionFactory.createConnection(conf);
HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
//HBaseAdmin admin = new HBaseAdmin(conf);
return admin.tableExists(tableName);
}
(3). 创建表
public static void createTable(String tableName, String... columnFamily) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
HBaseAdmin admin = new HBaseAdmin(conf);
//判断表是否存在
if(isTableExist(tableName)){
System.out.println("表" + tableName + "已存在");
//System.exit(0);
}else{
//创建表属性对象,表名需要转字节
HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
//创建多个列族
for(String cf : columnFamily){
descriptor.addFamily(new HColumnDescriptor(cf));
}
//根据对表的配置,创建表
admin.createTable(descriptor);
System.out.println("表" + tableName + "创建成功!");
}
}
(4).删除表
public static void dropTable(String tableName) throws Exception{
HBaseAdmin admin = new HBaseAdmin(conf);
if(isTableExist(tableName)){
admin.disableTable(tableName);
admin.deleteTable(tableName);
System.out.println("表" + tableName + "删除成功!");
}else{
System.out.println("表" + tableName + "不存在!");
}
}
(5).向表中插入数据
public static void addRowData(String tableName, String rowKey, String columnFamily, String column, String value) throws Exception{
//创建HTable对象
HTable hTable = new HTable(conf, tableName);
//向表中插入数据
Put put = new Put(Bytes.toBytes(rowKey));
//向Put对象中组装数据
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
hTable.put(put);
hTable.close();
System.out.println("插入数据成功");
}
(6).删除多行数据
public static void deleteMultiRow(String tableName, String... rows) throws IOException{
HTable hTable = new HTable(conf, tableName);
List deleteList = new ArrayList();
for(String row : rows){
Delete delete = new Delete(Bytes.toBytes(row));
deleteList.add(delete);
}
hTable.delete(deleteList);
hTable.close();
}
(7). 得到所有数据
public static void getAllRows(String tableName) throws IOException{
HTable hTable = new HTable(conf, tableName);
//得到用于扫描region的对象
Scan scan = new Scan();
//使用HTable得到resultcanner实现类的对象
ResultScanner resultScanner = hTable.getScanner(scan);
for(Result result : resultScanner){
Cell[] cells = result.rawCells();
for(Cell cell : cells){
//得到rowkey
System.out.println("行键:" + Bytes.toString(CellUtil.cloneRow(cell)));
//得到列族
System.out.println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
}
}
}
(8). 得到某一行所有数据
public static void getRow(String tableName, String rowKey) throws IOException{
HTable table = new HTable(conf, tableName);
Get get = new Get(Bytes.toBytes(rowKey));
//get.setMaxVersions();显示所有版本
//get.setTimeStamp();显示指定时间戳的版本
Result result = table.get(get);
for(Cell cell : result.rawCells()){
System.out.println("行键:" + Bytes.toString(result.getRow()));
System.out.println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
System.out.println("时间戳:" + cell.getTimestamp());
}
}
(9). 获取某一行指定“列族:列”的数据
public static void getRowQualifier(String tableName, String rowKey, String family, String qualifier) throws IOException{
HTable table = new HTable(conf, tableName);
Get get = new Get(Bytes.toBytes(rowKey));
get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
Result result = table.get(get);
for(Cell cell : result.rawCells()){
System.out.println("行键:" + Bytes.toString(result.getRow()));
System.out.println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
}
}
3 完整程序:
(1)HBaseUtil
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.TreeSet;
/**
*
* 1、NameSpace ====> 命名空间
* 2、createTable ===> 表
* 3、isTable ====> 判断表是否存在
* 4、Region、RowKey、分区键
*/
public class HBaseUtil {
/**
* 初始化命名空间
*
* @param conf 配置对象
* @param namespace 命名空间的名字
* @throws Exception
*/
public static void initNameSpace(Configuration conf, String namespace) throws Exception {
Connection connection = ConnectionFactory.createConnection(conf);
Admin admin = connection.getAdmin();
//命名空间描述器
NamespaceDescriptor nd = NamespaceDescriptor
.create(namespace)
.addConfiguration("AUTHOR", "Movle")
.build();
//通过admin对象来创建命名空间
admin.createNamespace(nd);
System.out.println("已初始化命名空间");
//关闭两个对象
close(admin, connection);
}
/**
* 关闭admin对象和connection对象
*
* @param admin 关闭admin对象
* @param connection 关闭connection对象
* @throws IOException IO异常
*/
private static void close(Admin admin, Connection connection) throws IOException {
if (admin != null) {
admin.close();
}
if (connection != null) {
connection.close();
}
}
/**
* 创建HBase的表
* @param conf
* @param tableName
* @param regions
* @param columnFamily
*/
public static void createTable(Configuration conf, String tableName, int regions, String... columnFamily) throws IOException {
Connection connection = ConnectionFactory.createConnection(conf);
Admin admin = connection.getAdmin();
//判断表
if (isExistTable(conf, tableName)) {
return;
}
//表描述器 HTableDescriptor
HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
for (String cf : columnFamily) {
//列描述器 :HColumnDescriptor
htd.addFamily(new HColumnDescriptor(cf));
}
//htd.addCoprocessor("hbase.CalleeWriteObserver");
//创建表
admin.createTable(htd,genSplitKeys(regions));
System.out.println("已建表");
//关闭对象
close(admin,connection);
}
/**
* 分区键
* @param regions region个数
* @return splitKeys
*/
private static byte[][] genSplitKeys(int regions) {
//存放分区键的数组
String[] keys = new String[regions];
//格式化分区键的形式 00 01 02
DecimalFormat df = new DecimalFormat("00");
for (int i = 0; i < regions; i++) {
keys[i] = df.format(i) + "";
}
byte[][] splitKeys = new byte[regions][];
//排序 保证你这个分区键是有序得
TreeSet treeSet = new TreeSet(Bytes.BYTES_COMPARATOR);
for (int i = 0; i < regions; i++) {
treeSet.add(Bytes.toBytes(keys[i]));
}
//输出
Iterator iterator = treeSet.iterator();
int index = 0;
while (iterator.hasNext()) {
byte[] next = iterator.next();
splitKeys[index++]= next;
}
return splitKeys;
}
/**
* 判断表是否存在
* @param conf 配置 conf
* @param tableName 表名
*/
public static boolean isExistTable(Configuration conf, String tableName) throws IOException {
Connection connection = ConnectionFactory.createConnection(conf);
Admin admin = connection.getAdmin();
boolean result = admin.tableExists(TableName.valueOf(tableName));
close(admin, connection);
return result;
}
}
(2) PropertiesUtil
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
public static Properties properties = null;
static {
//获取配置文件、方便维护
InputStream is = ClassLoader.getSystemResourceAsStream("hbase_consumer.properties");
properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取参数值
* @param key 名字
* @return 参数值
*/
public static String getProperty(String key){
return properties.getProperty(key);
}
}
(3) hbase_consumer.properties
# 设置Hbase的一些变量
hbase.calllog.regions=6
hbase.calllog.namespace=aa
hbase.calllog.tablename=Movle
(4) HBaseDAO
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
public class HBaseDAO {
private static String namespace = PropertiesUtil.getProperty("hbase.calllog.namespace");
private static String tableName = PropertiesUtil.getProperty("hbase.calllog.tablename");
private static Integer regions = Integer.valueOf(PropertiesUtil.getProperty("hbase.calllog.regions"));
public static void main(String[] args) throws Exception {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.property.clientPort", "2181");
conf.set("hbase.zookeeper.quorum", "hadoop1");
conf.set("zookeeper.znode.parent", "/hbase");
if (!HBaseUtil.isExistTable(conf, tableName)) {
HBaseUtil.initNameSpace(conf, namespace);
HBaseUtil.createTable(conf, tableName, regions, "f1", "f2");
}
}
}
7.运行结果:
运行HBaseDAO中的main函数: