@Data
@HBaseTable
public class User {
@Rowkey
private String id;
@HBaseColumn
private String name;
@HBaseColumn
private String address;
@HBaseColumn
private Integer age;
@HBaseColumn
private Date birthday;
}
public class HBaseUtilTest {
private HBaseUtil hbaseUtil;
@Before
public void init() {
HBaseConnectionFactory factory = new HBaseConnectionFactory();
factory.setProperties();
hbaseUtil = new HBaseUtil();
}
// 创建表
@Test
public void createTable() {
Set familyColumn = new HashSet<>(1);
familyColumn.add("info");
hbaseUtil.createTable("soul", familyColumn);
}
// 删除表
@Test
public void dropTable() {
System.out.println(hbaseUtil.dropTable("user"));
}
// 保存数据时检查表是否存在不存在则创建
@Test
public void saveCheck() {
List userList = new ArrayList<>(10);
Random r = new Random();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setId(StringUtil.ratedLength((i + 1) + "", 6, "0", 0));
user.setName("张" + user.getId());
user.setAddress("北京");
user.setAge(r.nextInt(58));
user.setBirthday(new Date());
userList.add(user);
}
hbaseUtil.saveCheck(userList);
}
// 保存数据
@Test
public void save() {
List userList = new ArrayList<>(10);
Random r = new Random();
for (int i = 10; i < 20; i++) {
User user = new User();
user.setId(StringUtil.ratedLength((i + 1) + "", 6, "0", 0));
user.setName("张" + user.getId());
user.setAddress("北京");
user.setAge(r.nextInt(58));
user.setBirthday(new Date());
userList.add(user);
}
hbaseUtil.save(userList);
get();
}
// 按rowkey删除数据
@Test
public void delete() {
System.out.println(hbaseUtil.delete("user", "000012", "000013", "000014", "000015", "000016", "000017", "000018", "000019", "000020"));
}
// 按rowkey查询数据
@Test
public void get() {
List userList = hbaseUtil.get("user", User.class, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
System.out.println(userList);
}
// 进行复杂查询
@Test
public void scan() throws IOException {
Scan scan = new Scan();
// 指定开始的行。如果不调用,则从表头开始
scan.setStartRow(Bytes.toBytes("000006"));
// 指定结束的行(不含此行)
//scan.setStopRow(Bytes.toBytes("000011"));
// 指定最多返回的Cell数目。用于防止一行中有过多的数据,导致OutofMemory错误
scan.setBatch(4);
// 指定最大的时间戳和最小的时间戳, 只有在此范围内的cell才能被获取
scan.setTimeRange(1598000011298L, 1598000693504L);
// 指定时间戳
//scan.setTimeStamp(1598000011299L);
// 指定Filter来过滤掉不需要的信息
//PageFilter pageFilter = new PageFilter(5);
//scan.setFilter(pageFilter);
List userList = hbaseUtil.scan("user", User.class, scan);
System.out.println(userList);
}
}