HBase在存儲(chǔ)數(shù)據(jù)時(shí),沒(méi)有數(shù)據(jù)類(lèi)型!以字節(jié)數(shù)組存儲(chǔ)
"cf".getBytes();
Bytes.toBytes("cf");
環(huán)境準(zhǔn)備
(1)制作hbase的用戶(hù)庫(kù),并導(dǎo)入
(2)導(dǎo)入hadoop用戶(hù)庫(kù)
(3)導(dǎo)入Junit測(cè)試庫(kù)
(4)src目錄中拷貝,build source file.hdfs-site.xml、hbase-site.sh、regionservers、backup-masters4個(gè)文件
HBaseDemo
public class HBaseDemo {
HBaseAdmin admin;
HTable htable;
String TN = "phone"; // 表名
@Before
public void init() throws Exception {
Configuration conf = new Configuration();
// 設(shè)置zk配置信息,必須配置,否則無(wú)法定位
conf.set("hbase.zookeeper.quorum", "node002,node003,node004");
admin = new HBaseAdmin(conf);
htable = new HTable(conf, TN.getBytes());
}
@Test
public void creatTable() throws Exception {
if (admin.tableExists(TN)) {
admin.disableTable(TN);
admin.deleteTable(TN);
System.out.println("table exists!");
}
// 表描述
HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(TN));
// 列族
HColumnDescriptor cf = new HColumnDescriptor("cf".getBytes());
desc.addFamily(cf);
// 創(chuàng)建表
admin.createTable(desc);
System.out.println("create table success!");
}
@Test
public void insertDB() throws Exception {
String rowKey = "111111";
Put put = new Put(rowKey.getBytes());
put.add("cf".getBytes(), "name".getBytes(), "xiaohong".getBytes());
put.add("cf".getBytes(), "age".getBytes(), "23".getBytes());
put.add("cf".getBytes(), "sex".getBytes(), "women".getBytes());
htable.put(put);
}
@Test
public void getDB() throws Exception {
String rowKey = "111111";
Get get = new Get(rowKey.getBytes());
// 獲取指定的列,不指定的列不去查,開(kāi)發(fā)必須寫(xiě)!不寫(xiě)是全部列!
// 就像 select *
get.addColumn("cf".getBytes(), "name".getBytes());
get.addColumn("cf".getBytes(), "age".getBytes());
get.addColumn("cf".getBytes(), "sex".getBytes());
Result rs = htable.get(get);
Cell cell = rs.getColumnLatestCell("cf".getBytes(), "name".getBytes());
Cell cell2 = rs.getColumnLatestCell("cf".getBytes(), "age".getBytes());
Cell cell3 = rs.getColumnLatestCell("cf".getBytes(), "sex".getBytes());
// System.out.println(new String(cell.getValue())); 過(guò)期了,用下面的工具類(lèi)
System.out.println(new String(CellUtil.cloneValue(cell)));
System.out.println(new String(CellUtil.cloneValue(cell2)));
System.out.println(new String(CellUtil.cloneValue(cell3)));
}
@Test
public void scan() throws IOException {
Scan scan = new Scan();
ResultScanner scanner = htable.getScanner(scan);
for (Result rs : scanner) {
System.out.println("掃描結(jié)果: "+rs);
}
}
@After
public void destory() throws Exception {
if (admin != null) {
admin.close();
}
}
}
掃描結(jié)果: keyvalues={111111/cf:age/1543959930854/Put/vlen=2/mvcc=0, 111111/cf:name/1543959930854/Put/vlen=8/mvcc=0, 111111/cf:sex/1543959930854/Put/vlen=5/mvcc=0}