public class FilterTest {
//操作表数据CRUD
private Connection conn;
//操作表 创建,删除表
private Admin admin;
/**
* 初始化连接
*/
@Before
public void init() throws IOException {
Configuration conf = HBaseConfiguration.create();
//创建连接
conn = ConnectionFactory.createConnection(conf);
//获取admin
admin = conn.getAdmin();
}
/**
* 插入数据,一次想插入10000条
*/
@Test
public void insert() throws Exception {
HTable table = (HTable) conn.getTable(TableName.valueOf("ns1:t1"));
ArrayList<Put> list = new ArrayList<Put>();
Put put;
for(int i = 1;i<10000;i++) {
put = new Put(Bytes.toBytes("row"+i));
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("id"), Bytes.toBytes("row"+i));
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("name"), Bytes.toBytes("tom"+i));
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("age"), Bytes.toBytes(i%100));
list.add(put);
}
table.put(list);
table.close();
}
/**
* 扫描数据
*/
@Test
public void scan() throws Exception {
//获取表
HTable table = (HTable) conn.getTable(TableName.valueOf("ns1:t1"));
//设置起始行和结束行
Scan scan = new Scan(Bytes.toBytes("row1"), Bytes.toBytes("row2"));
ResultScanner rs = table.getScanner(scan);
Iterator<Result> it = rs.iterator();
//迭代数据
while(it.hasNext()) {
Result r = it.next();
String id = Bytes.toString(r.getValue(Bytes.toBytes("f1"), Bytes.toBytes("id")));
String name = Bytes.toString(r.getValue(Bytes.toBytes("f1"), Bytes.toBytes("name")));
int age = Bytes.toInt(r.getValue(Bytes.toBytes("f1"), Bytes.toBytes("age")));
System.out.println(id+" "+name+" " +age);
}
}
/**
* 扫描数据,使用行列缓存
*/
@Test
public void scanWithCashing() throws Exception {
HTable table = (HTable) conn.getTable(TableName.valueOf("ns1:t1"));
Scan scan = new Scan(Bytes.toBytes("row1"), Bytes.toBytes("row2"));
//设置行缓存 一次RPC请求多少行数据
scan.setCaching(10);
//设置列缓存 一次RPC请求多少列数据
scan.setBatch(3);
ResultScanner rs = table.getScanner(scan);
Iterator<Result> it = rs.iterator();
while(it.hasNext()) {
Result r = it.next();
String id = Bytes.toString(r.getValue(Bytes.toBytes("f1"), Bytes.toBytes("id")));
String name = Bytes.toString(r.getValue(Bytes.toBytes("f1"), Bytes.toBytes("name")));
int age = Bytes.toInt(r.getValue(Bytes.toBytes("f1"), Bytes.toBytes("age")));
System.out.println(id+" "+name+" " +age);
}
}
/**
* 关闭连接
*/
@After
public void close() throws IOException {
admin.close();
conn.close();
}
}