public class Demo { private Configuration conf; private Connection conn; @Before public void prepare() throws Exception { conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum", "m6,m7,m8"); conn = ConnectionFactory.createConnection(conf); } /** * 创建表 */ @Test public void createTable() throws Exception { Admin admin = conn.getAdmin(); TableName tableName = TableName.valueOf("t_person"); HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName); // 添加列簇 HColumnDescriptor baseInfo = new HColumnDescriptor("base_info"); hTableDescriptor.addFamily(baseInfo); admin.createTable(hTableDescriptor); admin.close(); conn.close(); } /** * 删除表 * @throws Exception */ @Test public void dropTable() throws Exception { Admin admin = conn.getAdmin(); admin.disableTable(TableName.valueOf("t_person")); admin.deleteTable(TableName.valueOf("t_person")); admin.close(); } /** * 插入数据 * @throws Exception */ @Test public void put() throws Exception { TableName tableName = TableName.valueOf("t_person"); // HTablePool pool = new HTablePool(conf, 10); // HTable table = (HTable) pool.getTable("t_person"); Table table = conn.getTable(tableName); // rowkey 行健 Put put = new Put(Bytes.toBytes("p_0001")); put.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("name"), Bytes.toBytes("zhangsan")); put.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("age"), Bytes.toBytes(18)); table.put(put); table.close(); } /** * 获取数据 * @throws IOException */ @Test public void get() throws IOException { TableName tableName = TableName.valueOf("t_person"); Table table = conn.getTable(tableName); Get get = new Get(Bytes.toBytes("p_0001")); Result result = table.get(get); for (Cell cell : result.listCells()) { System.out.println(Bytes.toString(CellUtil.cloneFamily(cell))); System.out.println(Bytes.toString(CellUtil.cloneQualifier(cell))); System.out.println(Bytes.toInt(CellUtil.cloneValue(cell))); } } @Test public void scan() throws IOException { TableName tableName = TableName.valueOf("t_person"); Table table = conn.getTable(tableName); Scan scan = new Scan(); // 根据Qualifier的开头字符进行过滤 ColumnPrefixFilter filter = new ColumnPrefixFilter(Bytes.toBytes("z")); scan.setFilter(filter); ResultScanner scanner = table.getScanner(scan); for (Result result : scanner) { for (Cell cell : result.listCells()) { System.out.println(Bytes.toString(CellUtil.cloneFamily(cell))); System.out.println(Bytes.toString(CellUtil.cloneQualifier(cell))); } } } }