第一步:创建项目 导入需要的jar包
第二步:代码如下:
package com.xjtuse.hbase;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestHbase {
public static Connection conn = null;
public static TableName test3 = TableName.valueOf("test3");
public static Random random = new Random();
@Before
// 初始化
public void init() throws IOException{
Configuration conf = HBaseConfiguration.create();
// 指定zookeeper集群在哪些节点上
conf.set("hbase.zookeeper.quorum", "master,slave1,slave2");
// 设置zookeeper的端口
conf.set("hbase.zookeeper.property.clientPort", "2181");
conn = ConnectionFactory.createConnection(conf);
}
@Test
// 创建表格
public void create() throws IOException {
// 创建表管理类
Admin admin = conn.getAdmin();
// 如果表存在 则禁用并删除它
if(admin.tableExists(test3)){
admin.disableTable(test3);
admin.deleteTable(test3);
}
// 创建列族描述类
HTableDescriptor ht = new HTableDescriptor(test3);
// 创建列族
HColumnDescriptor hc = new HColumnDescriptor("cf1".getBytes());
hc.setMaxVersions(5);
hc.setBlockCacheEnabled(true);
hc.setBlocksize(1800000);
ht.addFamily(hc);
admin.createTable(ht);
admin.close();
}
// 生成随机rowkey的方法
public String getRowKey(String pre){
return pre+ random.nextInt(99999999)+"_2018"+random.nextInt(12)+random.nextInt(30)+random.nextInt(24)+random.nextInt(60)+random.nextInt(60);
}
@Test
// 插入数据
public void insert() throws IOException {
Table table = conn.getTable(test3);
List<Put> list = new ArrayList<Put>();
for(int i=0;i<100;i++){
Put put = new Put(getRowKey("138").getBytes());
put.addColumn("cf1".getBytes(),"address".getBytes(),"北京".getBytes());
put.addColumn("cf1".getBytes(),"type".getBytes(),String.valueOf(random.nextInt(2)).getBytes());
list.add(put);
}
table.put(list);
}
@Test
// 根据rowkey查询数据
public void find() throws IOException {
Table table = conn.getTable(test3);
Scan scan = new Scan("13880137465_20184293492".getBytes(),"13880137465_20184293492".getBytes());
ResultScanner scanner = table.getScanner(scan);
Iterator<Result> it = scanner.iterator();
while(it.hasNext()){
Result next = it.next();
byte[] value = next.getValue("cf1".getBytes(), "type".getBytes());
System.out.println(new String(value,"GBK"));
}
}
@Test
// 根据rowkey删除数据
public void delete() throws IOException
{
Table table = conn.getTable(test3);
Delete delete = new Delete("13880137465_20184293492".getBytes());
table.delete(delete);
}
}