1.pom
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.5</version>
</dependency>
2.api
public static void create() {
Configuration conf = new Configuration();
conf.set("hbase.zookeeper.quorum", "localhost:2181");
try {
//连接hbase
Connection con = ConnectionFactory.createConnection(conf);
//获取t01表
HBaseAdmin admin = (HBaseAdmin) con.getAdmin();
String tableName = "t1";
if (admin.tableExists("t1")) {
admin.disableTable("t1");
admin.deleteTable(tableName);
System.out.println("Table exists!");
}
HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf("t1"));
tableDesc.addFamily(new HColumnDescriptor("cf".getBytes()));
admin.createTable(tableDesc);
System.out.println("create table success!");
admin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void insert() throws IOException {
Configuration conf = new Configuration();
conf.set("hbase.zookeeper.quorum", "localhost:2181");
//获取t01表
HTable hTable = new HTable(conf,"t1");
String rowKey = "2222";
Put put = new Put(rowKey.getBytes());
put.addColumn("cf".getBytes(), "name".getBytes(), "xiaohong".getBytes());
put.addColumn("cf".getBytes(), "age".getBytes(), "23".getBytes());
put.addColumn("cf".getBytes(), "sex".getBytes(), "women".getBytes());
hTable.put(put);
hTable.close();
}
public static void get() throws IOException {
Configuration conf = new Configuration();
conf.set("hbase.zookeeper.quorum", "localhost:2181");
Connection connection = ConnectionFactory.createConnection(conf); //config为前文的配置对象
TableName tableName = TableName.valueOf("t1");
Table table= connection.getTable(tableName);
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 = table.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)));
table.close();
connection.close();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)