maven依赖
如果仅仅是为了测试练习java操作Hbase,只需要导入一下依赖即可
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
通用代码
以下代码是测试时用到的配置代码,一个类中只需要用一次。为了方便,也可以写成静态的。
private static Admin admin; //负责执行ddl
private static Connection connection; //表示连接,访问Hbase的入口 执行dml指令时用到
@Before
public void before() throws IOException {
//Hadoop的配置文件管理系统 也就是Configuration用来处理配置文件信息
Configuration configuration = new Configuration();
//hbase使用zookeeper的地址 在windows中可以将Linux下的用户名和IP进行映射
configuration.set("hbase.zookeeper.quorum","Hbase");
//将配置信息交由工厂管理
connection = ConnectionFactory.createConnection(configuration);
//获得admin管理
admin = connection.getAdmin();
}
@After
public void after() throws IOException {
admin.close();
connection.close();
}
Namespace相关操作
下面的代码是关于Namespace的一些常用操作
这些代码不用死记,理解着来就可以。
比较实用的方法是,用反推法来写。
比如,创建Namespace。
首先可以先写 admin.createNamespace(nd); 它是用来创建Namespace的总的命令。 在通过查看所需要的参数为nd。之后我们可以再写nd相关的代码。
//创建namespace
@Test
public void createNamespace() throws IOException {
//创建namespace,设置名字,以及描述
NamespaceDescriptor nd = NamespaceDescriptor.create("zpark")
.addConfiguration("user","zhangsan")
.build();
//进行创建
admin.createNamespace(nd);
}
//查看namespace
@Test
public void queryNamespace() throws IOException {
//获得所有的Namespace的信息
NamespaceDescriptor[] nd = admin.listNamespaceDescriptors();
for (NamespaceDescriptor namespaceDescriptor : nd) {
//打印出Namespace的名字
System.out.println(namespaceDescriptor.getName());
}
}
//删除
@Test
public void delNamespace() throws IOException {
admin.deleteNamespace("zpark");
}
Table相关操作
下面是Table的相关操作
总的步骤就是,创建列簇,将列簇添加到HTableDescriptor的API中,执行创建。
//创建Table
@Test
public void createTable() throws IOException {
TableName tableName = TableName.valueOf("zpark:t_user");
HTableDescriptor hd = new HTableDescriptor(tableName);
//创建列簇cf1、cf2
HColumnDescriptor cf1 = new HColumnDescriptor("cf1");
//版本数
cf1.setMaxVersions(3);
//设置是否添加到内存中,以提高读取效率
cf1.setInMemory(true);
HColumnDescriptor cf2 = new HColumnDescriptor("cf2");
//存活时间
cf2.setMaxVersions(3);
cf2.setBloomFilterType(BloomType.ROWCOL);
//添加列簇
hd.addFamily(cf1);
hd.addFamily(cf2);
admin.createTable(hd);
}
//删除Table
@Test
public void delete() throws IOException {
TableName tableName = TableName.valueOf("zpark:t_user");
//如果没有关闭表,先将表失效
if(!admin.isTableDisabled(tableName)) {
admin.disableTable(tableName);
}
admin.deleteTable(tableName);
}
数据相关操作
//put 此方法不推荐 与Hbase的交互次数太多 导致Hbase的压力变大
@Test
public void put() throws IOException {
String[] depts = {"研发", "UI", "销售", "保安"};
Table table = connection.getTable(TableName.valueOf("zpark:t_user"));
//构建put指令
for(int i = 100 ; i<200 ; i++ ){
//可以依次顺序生成三位数
DecimalFormat df = new DecimalFormat("000");
//将这些数字作为行键
String rowKey = df.format(i);
//添加数据
Put put = new Put(rowKey.getBytes());
//设置姓名
put.addColumn("cf2".getBytes(),"name".getBytes(),("zhangsan"+rowKey).getBytes());
//设置性别
put.addColumn("cf2".getBytes(),"sex".getBytes(),((i%4==0)+"").getBytes());
//设置年龄
put.addColumn("cf2".getBytes(),"age".getBytes(),(i+"").getBytes());
//设置部门
put.addColumn("cf2".getBytes(),"dept".getBytes(),((i%4)+"").getBytes());
//设置工资
put.addColumn("cf2".getBytes(),"salary".getBytes(),((i*100)+"").getBytes());
//添加
table.put(put);
}
table.close();
}
//批量插入 先将数据存入缓冲区中 在批量进行添加
@Test
public void movePut() throws IOException {
BufferedMutator bufferedMutator = connection.getBufferedMutator(TableName.valueOf("zpark:t_user"));
//构建put指令
for(int i = 100 ; i<1000 ; i++ ){
DecimalFormat df = new DecimalFormat("000");
String rowKey = df.format(i);
Put put = new Put(rowKey.getBytes());
put.addColumn("cf2".getBytes(),"name".getBytes(),("zhangsan"+rowKey).getBytes());
put.addColumn("cf2".getBytes(),"sex".getBytes(),((i%4==0)+"").getBytes());
put.addColumn("cf1".getBytes(),"age".getBytes(),(i+"").getBytes());
put.addColumn("cf1".getBytes(),"dept".getBytes(),((i%4)+"").getBytes());
bufferedMutator.mutate(put);
if(i%500==0){
bufferedMutator.flush();
}
}
bufferedMutator.close();
}
@Test
//get 展示该行键对应的列值的详细信息 复杂版
public void get() throws IOException {
Table table = connection.getTable(TableName.valueOf("zpark:t_user"));
//查询行键002的数据
Get get = new Get("002".getBytes());
//接收到的结果
Result result = table.get(get);
//遍历
while (result.advance()){
//相当于读取到的行数据
Cell cell = result.current();
String row = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
long timestamp = cell.getTimestamp();
System.out.println(row+"=>"+family+":"+qualifier+"\t"+value+" ts:"+timestamp);
}
table.close();
}
// 简化版
@Test
public void get2() throws IOException {
Table table = connection.getTable(TableName.valueOf("zpark:t_user"));
Get get = new Get("002".getBytes());
Result result = table.get(get);
String row = Bytes.toString(result.getRow());
String name = Bytes.toString(result.getValue("cf1".getBytes(), "name".getBytes()));
String age = Bytes.toString(result.getValue("cf1".getBytes(), "age".getBytes()));
String sex = Bytes.toString(result.getValue("cf1".getBytes(), "sex".getBytes()));
String dept = Bytes.toString(result.getValue("cf1".getBytes(), "dept".getBytes()));
System.out.println(row+"\t"+name+" "+age+" "+sex+" "+dept);
table.close();
}
//scan 利用过滤器来过滤出指定条件的数据
@Test
public void scan() throws IOException {
Table table = connection.getTable(TableName.valueOf("zpark:t_user"));
Scan scan = new Scan();
//开始行
scan.setStartRow("000".getBytes());
//结束行
scan.setStopRow("999".getBytes());
scan.addFamily("cf1".getBytes());
//以09结尾
Filter filter1 = new RowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator("09$"));
//包含80
Filter filter2 = new RowFilter(CompareFilter.CompareOp.EQUAL, new SubstringComparator("80"));
FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ONE, filter1, filter2);
scan.setFilter(filterList);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
String row=Bytes.toString(result.getRow());
String name = Bytes.toString(result.getValue("cf1".getBytes(), "name".getBytes()));
String age = Bytes.toString(result.getValue("cf1".getBytes(), "age".getBytes()));
String sex = Bytes.toString(result.getValue("cf1".getBytes(), "sex".getBytes()));
String dept = Bytes.toString(result.getValue("cf1".getBytes(), "dept".getBytes()));
System.out.println(row+"\t"+name+" "+age+" "+sex+" "+dept);
}
table.close();
}
以上是基本的操作,还有很多的API,可以自行尝试。