package com.ls.hbase;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.List;
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.KeyValue;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseApp {
static String TABLE_NAME = "htableTest";//表名称
static String familyName = "info";//列簇名称
public static void main(String[] args) throws Exception{
Configuration conf = HBaseConfiguration.create();
conf.setStrings("hbase.zookeeper.quorum", "server2");
scan(conf);
}
/***
* 新增数据
* @param conf
* @throws IOException
* @throws InterruptedIOException
* @throws RetriesExhaustedWithDetailsException
*/
private static void insert(Configuration conf) throws Exception{
HTable htable = new HTable(conf,TABLE_NAME);
//指定ROWKEY的值
Put put = new Put(Bytes.toBytes("xiaoming"));
//指定列簇名称、列修饰符、列值
put.add(familyName.getBytes(), "age".getBytes(), "24".getBytes());
htable.put(put);
}
/***
* 创建/删除表语句
* @param conf
* @throws Exception
*/
private static void createOrDelete(Configuration conf)throws Exception {
HBaseAdmin admin = new HBaseAdmin(conf);
HTableDescriptor htableDes = new HTableDescriptor(TABLE_NAME);
HColumnDescriptor familyDesc = new HColumnDescriptor(familyName);
htableDes.addFamily(familyDesc);
//如果表不存在则创建表
if(!admin.tableExists(TABLE_NAME)){
admin.createTable(htableDes);
}
//删除表(先将表进行disable处理,然后才能delete操作)
// admin.disableTable(TABLE_NAME);
// admin.deleteTable(TABLE_NAME);
//关闭操作
admin.close();
}
/***
* 浏览表
* @param conf
* @throws IOException
*/
private static void scan(Configuration conf) throws IOException {
HTable table = new HTable(conf,TABLE_NAME);
Scan scan = new Scan();
scan.setStartRow("xiaohua".getBytes());
scan.setStopRow("xiaohua2".getBytes());
//全表扫描
ResultScanner scanner = table.getScanner(scan);
for(Result result :scanner){
List<KeyValue> column = result.getColumn("info".getBytes(), "age".getBytes());
System.out.println(column);
}
}
}