通過Java 操作Hbase
一潘悼、版本:
hbase:
二喉悴、操作Hbase:
1祸挪、首先定義幾個(gè)用的到的全局變量:
HBaseAdmin :主要對于表的一些設(shè)置操作
HBaseAdmin hBaseAdmin;
HTable:主要涉及到對標(biāo)內(nèi)容的操作
HTable hTable;
TN:測試的表名
String TN = "lillcol";
2外潜、創(chuàng)建begin()方法初始化資源:
//初始化Configuration? hBaseAdmin hTable
public void begin() throws Exception {
Configuration conf = new Configuration();
// conf.set("hbase.zookeeper.quorum", "node1.noce2.noce3");
hBaseAdmin = new HBaseAdmin(conf);
hTable = new HTable(conf, TN);
}
3原环、創(chuàng)建end()方法關(guān)閉資源:
//關(guān)閉hBaseAdmin? hTable 資源 注意先判斷是否為null
public void end() {
if (hBaseAdmin != null) {
try {
hBaseAdmin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (hTable != null) {
try {
hTable.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4、創(chuàng)建一個(gè)Table
注:不同版本可能會有不一樣的方法处窥,此方法適合0.9的嘱吗,至于1.0是否能用后面會嘗試?
//創(chuàng)建一個(gè)新的Table
public void createTable() throws Exception {
//初始化
begin();
//首先判斷表存不存在? 存在刪除
if (hBaseAdmin.tableExists(TN)) {
hBaseAdmin.disableTable(TN);
hBaseAdmin.deleteTable(TN);
}
//1.2以后的版本 好像不用 HTableDescriptor了
//過段時(shí)間在更新1.2以后的版本
HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(TN));
//創(chuàng)建列族
HColumnDescriptor family1 = new HColumnDescriptor("column1");
//對表的一些設(shè)置
family1.setBlockCacheEnabled(true);
family1.setInMemory(true);
family1.setMaxVersions(2);
//添加列族
desc.addFamily(family1);
hBaseAdmin.createTable(desc);
System.out.println("create table success");
//關(guān)閉資源
end();
}
5、模擬插入數(shù)據(jù)(參考了尚學(xué)堂的學(xué)習(xí)資料 模擬數(shù)據(jù))
// 獲得手機(jī)號? ?
?public String getPhoneNum(String prefix) {? ? ? ??
return prefix + String.format("%8d", r.nextInt(999999999));
? ? }?
?? //獲得日期? ? public String getDate(String year) {?
?? ? ? return year+ String.format( ?"%02d%02d%02d%02d%02d", new Object[] { r.nextInt(12) + 1, r.nextInt(29) + 1, r.nextInt(60), r.nextInt(60), r.nextInt(60) });? ? }?
?? public void insertDB() throws Exception {??
? ? ? begin();? ?
?? // 創(chuàng)建一個(gè)List緩存? ? ?
?? Listputs = new ArrayList();
//為一個(gè)用戶生成十條模擬數(shù)據(jù)
for (int i = 0; i < 10; i++) {
String rowKey;
String phoneNum = getPhoneNum("186");
for (int j = 0; j < 100; j++) {
String phoneData = getDate("2016");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
try {
long dataLong = sdf.parse(phoneData).getTime();
rowKey = phoneNum + (Long.MAX_VALUE - dataLong);
// System.out.println(rowKey);
Put put = new Put(rowKey.getBytes());
put.add("column1".getBytes(), "name".getBytes(), "lillcol".getBytes());
//將入list緩存
puts.add(put);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//批量添加數(shù)據(jù)
hTable.put(puts);
end();
}
6滔驾、查詢數(shù)據(jù)
//查詢數(shù)據(jù)
public void scandDB() throws Exception {
begin();
Scan scan = new Scan();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//設(shè)置開始rowKey? 和結(jié)束rowKey
String startRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016010100000").getTime());
scan.setStartRow(startRowKey.getBytes());
String stopRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016020100000").getTime());
scan.setStopRow(stopRowKey.getBytes());
ResultScanner scanner = hTable.getScanner(scan);
for (Result rs : scanner) {
//rs.getColumnLatestCell("colmun1".getBytes(), "name".getBytes())) 獲取到的數(shù)據(jù)需要經(jīng)過CellUtil.cloneValue在轉(zhuǎn)換成String
System.out.println(new String(CellUtil.cloneValue(rs.getColumnLatestCell("colmun1".getBytes(),
"name".getBytes()))));
}
end();
}
7谒麦、帶過濾器的查詢
//具體的方法可以去看官網(wǎng)的文檔
//帶過濾器的查詢
public void scandDB2() throws Exception {
begin();
FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
PrefixFilter prefixFilter = new PrefixFilter("18827385967".getBytes());
list.addFilter(prefixFilter);
SingleColumnValueExcludeFilter singleColumnValueExcludeFilter = new SingleColumnValueExcludeFilter(
"colmun1".getBytes(), "name".getBytes(), CompareOp.EQUAL, "lillcol".getBytes());
list.addFilter(singleColumnValueExcludeFilter);
Scan scan = new Scan();
scan.setFilter(list);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String startRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016010100000").getTime());
scan.setStartRow(startRowKey.getBytes());
String stopRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016020100000").getTime());
scan.setStopRow(stopRowKey.getBytes());
ResultScanner scanner = hTable.getScanner(scan);
for (Result rs : scanner) {
System.out.println(new String(CellUtil.cloneValue(rs.getColumnLatestCell("colmun1".getBytes(),
"name".getBytes()))));
}
end();
}
8、獲取某條數(shù)據(jù)
//獲取某條數(shù)據(jù)
public void get() throws Exception {
begin();
// 手機(jī)號_時(shí)間戳
String rowKey = "133456789755_20170932438765";
Get get = new Get(rowKey.getBytes());
get.addColumn("column1".getBytes(), "name".getBytes());
get.addColumn("column1".getBytes(), "age".getBytes());
Result result = hTable.get(get);
KeyValue columnLatest = result.getColumnLatest("column".getBytes(), "name".getBytes());
System.out.println("----------" + new String(CellUtil.cloneValue(columnLatest)));
end();
}
9哆致、main方法
public static void main(String[] args) throws Exception {
HbaseDemo hbaseDemo = new HbaseDemo();
System.out.println("create table main ");
hbaseDemo.createTable();
System.out.println("insert table main ");
hbaseDemo.insertDB();
}
10绕德、完整源碼
package cn.lillcol.sxt;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import java.util.Random;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.hbase.CellUtil;import org.apache.hadoop.hbase.HColumnDescriptor;import org.apache.hadoop.hbase.HTableDescriptor;import org.apache.hadoop.hbase.KeyValue;import org.apache.hadoop.hbase.TableName;import org.apache.hadoop.hbase.client.Get;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.Scan;import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;import org.apache.hadoop.hbase.filter.FilterList;import org.apache.hadoop.hbase.filter.PrefixFilter;import org.apache.hadoop.hbase.filter.SingleColumnValueExcludeFilter;
public class HbaseDemo {??
? HBaseAdmin hBaseAdmin;??
? HTable hTable; ?
?String TN = "lillcol";?
?? Random r = new Random();?
?? // 初始化
Configuration hBaseAdmin hTable? ??
public void begin() throws Exception {? ? ? ??
Configuration conf = new Configuration();? ??
//集群跑的時(shí)候不設(shè)置 ?本地需要設(shè)置 ??
?// conf.set("hbase.zookeeper.quorum", "node1.noce2.noce3");? ? ??
? hBaseAdmin = new HBaseAdmin(conf);? ? ??
? hTable = new HTable(conf, TN);??
? }??
? // 關(guān)閉hBaseAdmin hTable 資源 注意先判斷是否為null? ?
?public void end() {? ? ? ??
if (hBaseAdmin != null) {? ?
?? ? ? ? try {? ? ??
? ? ? ? ? hBaseAdmin.close();? ? ?
?? ? ? } catch (IOException e) {? ? ??
? ? ? ? ? // TODO Auto-generated catch block? ? ? ? ? ? ??
? e.printStackTrace();? ? ??
? ? ? }? ?
?? ? } ? ?
?? if (hTable != null) {? ? ? ?
?? ? try {? ? ? ? ?
?? ? ? hTable.close();? ? ? ? ? ?
?} catch (IOException e) { ?
?? ? ? ? ? ? // TODO Auto-generated catch block? ? ? ??
? ? ? ? e.printStackTrace();? ? ? ? ? ? }? ? ? ? }? ? }? ?
?// 創(chuàng)建一個(gè)新的Table? ??
public void createTable() throws Exception {? ?
?? ? // 初始化? ? ??
? begin();? ? ? ?
?// 首先判斷表存不存在 存在刪除? ? ??
? if (hBaseAdmin.tableExists(TN)) {? ??
? ? ? ? hBaseAdmin.disableTable(TN); ? ?
?? ? ? hBaseAdmin.deleteTable(TN);? ??
? ? }? ? ?
?? // 1.2以后的版本 好像不用 HTableDescriptor了? ??
? ? // 過段時(shí)間在更新1.2以后的版本? ? ?
?? HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(TN));??
? ? ? // 創(chuàng)建列族? ? ?
?? HColumnDescriptor family1 = new HColumnDescriptor("column1");? ?
?? ? // 對表的一些設(shè)置? ??
? ? family1.setBlockCacheEnabled(true);? ?
?? ? family1.setInMemory(true);? ??
? ? family1.setMaxVersions(2); ? ? ??
// 添加列族? ? 1.2版本好像不支持addFamily(方法了)
? ? desc.addFamily(family1);??
? ? ? hBaseAdmin.createTable(desc);??
? ? ? System.out.println("create table success");?
?? ? ? // 關(guān)閉資源? ?
?? ? end();? ? }? ?
?public void insert() throws Exception {? ?
?? ? begin();?
?? ? ? Listputs = new ArrayList();?
?? ? ? // 手機(jī)號_時(shí)間戳? ?
?? ? String rowKey = "133456789755_20170932438765"; ?
?? ? Put put = new Put(rowKey.getBytes());??
? ? ? put.add("column1".getBytes(), "name".getBytes(), "lillcol".getBytes());? ? ? ? put.add("column1".getBytes(), "age".getBytes(), "20".getBytes());??
? ? ? puts.add(put);??
? ? ? if (puts.size() > 10) {? ? ??
? ? ? hTable.put(puts);?
?? ? ? ? ? puts.removeAll(puts);??
? ? ? }??
? ? ? end();
? ? }??
? //獲取某條數(shù)據(jù)?
?? public void get() throws Exception {? ??
? ? begin(); ?
? ? ? // 手機(jī)號_時(shí)間戳? ? ??
? String rowKey = "133456789755_20170932438765";?
?? ? ? Get get = new Get(rowKey.getBytes());??
? ? ? get.addColumn("column1".getBytes(), "name".getBytes());??
? ? ? get.addColumn("column1".getBytes(), "age".getBytes());??
? ? ? Result result = hTable.get(get);?
?? ? ? KeyValue columnLatest = result.getColumnLatest("column".getBytes(), "name".getBytes());?
?? ? ? System.out.println("----------" + new String(CellUtil.cloneValue(columnLatest)));? ?
?? ? end();??
? }
? ? // 獲得手機(jī)號? ?
?public String getPhoneNum(String prefix) {? ??
? ? return prefix + String.format("%8d", r.nextInt(999999999));? ?
?}? ?
?//獲得日期? ?
?public String getDate(String year) {? ??
? ? return year + String.format( "%02d%02d%02d%02d%02d", new Object[] { r.nextInt(12) + 1, r.nextInt(29) + 1, r.nextInt(60), r.nextInt(60), ?r.nextInt(60) });??
? }??
? public void insertDB() throws Exception {? ??
? ? begin();? ?
?? // 創(chuàng)建一個(gè)List緩存? ? ?
?? Listputs = new ArrayList();
//為一個(gè)用戶生成十條模擬數(shù)據(jù)
for (int i = 0; i < 10; i++) {
String rowKey;
String phoneNum = getPhoneNum("186");
for (int j = 0; j < 100; j++) {
String phoneData = getDate("2016");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
try {
long dataLong = sdf.parse(phoneData).getTime();
rowKey = phoneNum + (Long.MAX_VALUE - dataLong);
// System.out.println(rowKey);
Put put = new Put(rowKey.getBytes());
put.add("column1".getBytes(), "name".getBytes(), "lillcol".getBytes());
//將入list緩存
puts.add(put);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//批量添加數(shù)據(jù)
hTable.put(puts);
end();
}
//查詢數(shù)據(jù)
public void scandDB() throws Exception {
begin();
Scan scan = new Scan();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//設(shè)置開始rowKey? 和結(jié)束rowKey
String startRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016010100000").getTime());
scan.setStartRow(startRowKey.getBytes());
String stopRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016020100000").getTime());
scan.setStopRow(stopRowKey.getBytes());
ResultScanner scanner = hTable.getScanner(scan);
for (Result rs : scanner) {
//rs.getColumnLatestCell("colmun1".getBytes(), "name".getBytes())) 獲取到的數(shù)據(jù)需要經(jīng)過CellUtil.cloneValue在轉(zhuǎn)換成String
System.out.println(new String(CellUtil.cloneValue(rs.getColumnLatestCell("colmun1".getBytes(),
"name".getBytes()))));
}
end();
}
//帶過濾器的查詢
public void scandDB2() throws Exception {
begin();
FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
PrefixFilter prefixFilter = new PrefixFilter("18827385967".getBytes());
list.addFilter(prefixFilter);
SingleColumnValueExcludeFilter singleColumnValueExcludeFilter = new SingleColumnValueExcludeFilter(
"colmun1".getBytes(), "name".getBytes(), CompareOp.EQUAL, "lillcol".getBytes());
list.addFilter(singleColumnValueExcludeFilter);
Scan scan = new Scan();
scan.setFilter(list);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String startRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016010100000").getTime());
scan.setStartRow(startRowKey.getBytes());
String stopRowKey = "18828394827" + (Long.MAX_VALUE - sdf.parse("2016020100000").getTime());
scan.setStopRow(stopRowKey.getBytes());
ResultScanner scanner = hTable.getScanner(scan);
for (Result rs : scanner) {
System.out.println(new String(CellUtil.cloneValue(rs.getColumnLatestCell("colmun1".getBytes(),
"name".getBytes()))));
}
end();
}
public static void main(String[] args) throws Exception {
HbaseDemo hbaseDemo = new HbaseDemo();
System.out.println("create table main ");
hbaseDemo.createTable();
System.out.println("insert table main ");
hbaseDemo.insertDB();
}
}
11、總結(jié)
由于剛接觸hbase不久 所以如果文中內(nèi)容有錯(cuò)誤的話 歡迎指出 ?謝謝
此外 此文主要是本人學(xué)習(xí)hbase過程中參考尚學(xué)堂教程的一些總結(jié)LА耻蛇!