HBase在存储数据时,没有数据类型!以字节数组存储
"cf".getBytes();
Bytes.toBytes("cf");
环境准备
(1)制作hbase的用户库,并导入
(2)导入hadoop用户库
(3)导入Junit测试库
(4)src目录中拷贝,build source file.hdfs-site.xml
、hbase-site.sh
、regionservers
、backup-masters
4个文件
HBaseDemo
public class HBaseDemo {
HBaseAdmin admin;
HTable htable;
String TN = "phone"; // 表名
@Before
public void init() throws Exception {
Configuration conf = new Configuration();
// 设置zk配置信息,必须配置,否则无法定位
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);
// 创建表
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());
// 获取指定的列,不指定的列不去查,开发必须写!不写是全部列!
// 就像 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())); 过期了,用下面的工具类
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("扫描结果: "+rs);
}
}
@After
public void destory() throws Exception {
if (admin != null) {
admin.close();
}
}
}
扫描结果: 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}
网友评论