javaAPI 操作Hbase基础篇

实体类 (使用了lombok框架)
lombok框架(插件)
该框架会根据注解,生成对应的getter/setter访问器,以及构造方法
注解名 作用
------------------------------------------------------------
@Data 标注在类上,用于生成getter/setter访问器
@NoArgsConstructor 标注在类上,用于生成无参数的构造方法
@AllArgsConstructor 标注在类上,用于生成有参数的构造方法

package TestHbase;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    private String rk;
    private int id;
    private String name;
    private int age;
}

基本用法

package TestHbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class DemoHbase {
	//HBase操作的入口类:Admin
   //HBase在1.x以下的版本的入口类是HBaseAdmin
    //在1.x之后的入口类Admin
    private Admin admin;
    private Connection connection;

    @Before
    public void setUp() throws IOException {
        Configuration configuration = HBaseConfiguration.create();
        connection= ConnectionFactory.createConnection(configuration);
        admin=connection.getAdmin();
    }
    @Test
    public void testEnv(){
        System.out.println("Admin的实例"+admin);
    }
    @Test
    public void createTable(){
        //步骤:
        //①TableName,封装了表名
        TableName tableName = TableName.valueOf("ns:tb_emp");
        //②HTableDescriptor,封装了表的描述
        HTableDescriptor desc =new HTableDescriptor(tableName);
        //③准备HColumnDescriptor,列簇
        HColumnDescriptor family = new HColumnDescriptor("cf");
        //④将列簇添加到表中
        desc.addFamily(family);
        //⑤建表
        try {
            admin.createTable(desc);
            System.out.println("恭喜创建tb_emp表成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    //查看所有表
    public void listAllTables() throws IOException {
        List<TableDescriptor> tableDescriptors = admin.listTableDescriptors();
        for (TableDescriptor td:tableDescriptors){
            //表名
            String tableName = td.getTableName().getNameAsString();
            System.out.println("!!!!!"+tableName);
            ColumnFamilyDescriptor[] columnFamilies = td.getColumnFamilies();
            //每循环一次,分析的是表中当前列簇的信息
            for (ColumnFamilyDescriptor cfd:
                 columnFamilies) {
                //列簇名
                String cfn = cfd.getNameAsString();
                //版本
                int maxVersions = cfd.getMaxVersions();
                int minVersions = cfd.getMinVersions();
                System.out.printf("表名:%s,列族名:%s,maxVersion:%d,minVersion:%d%n",tableName,cfn,maxVersions,minVersions);
            }
        }
    }
    /**
     * 向创建的表中增加记录(相当于在shell中执行put操作,这是一个dml的操作,这个dml或者dql的操作的入口类是HTable) (put)
     */

    public void insertRecordsIntoTable(String tableName, Emp emp) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tableName));
        //封装RowKey
        Put rk=new Put(Bytes.toBytes(emp.getRk()));
//        rk.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("id"),Bytes.toBytes("1"));
        //封装id
        // @param family family name
        // @param qualifier column qualifier
        // @param value column value  ~>若值是整型,需要将其转换成字符串,然后调用.getBytes()
        Put idPut = rk.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("id"), (emp.getId() + "").getBytes());
        //封装name
        Put namePut = rk.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes(emp.getName()));
        //封装age
        Put agePut = rk.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("age"), (emp.getAge() + "").getBytes());
        List<Put> list=new LinkedList<>();
        Collections.addAll(list,rk,idPut,idPut,namePut,agePut);
        try {
            table.put(list);
            System.out.println("恭喜添加纪录成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    //批量插入记录
    public void testInsert() throws IOException {
        String rk="rk00";
        String tableName="ns:tb_emp";
        for (int i = 1; i <101 ; i++) {
            insertRecordsIntoTable(tableName,new Emp("rk00"+i,i, "wb" + i, 19 + i));
        }
    }

    @Test
    //案例4,	查询所有(相当于执行scan命令)
    public void scanAll()throws IOException{
        //步骤:
        //①Scan
        Scan scan=new Scan();
        //②HTable
        HTable table = (HTable) connection.getTable(TableName.valueOf("ns:tb_emp"));
        //③查询HBase表,等价于:hbase shell指令之scan
        ResultScanner scanner = table.getScanner(scan);
        //④分析结果
        List<Emp> emps=new ArrayList<>();
        //每循环一次,取出一条记录,将其封装为Emp类的实例,并添加到容器中
        for (Result result:
             scanner) {
            //行键
            String rk = new String(result.getRow());
            int id = Integer.parseInt(new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("id"))));
            String name = new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("name")));
            int age = Integer.parseInt(new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("age"))));
            emps.add(new Emp(rk,id,name,age));
        }
        for (Emp e:
             emps) {
            System.out.println(e);
        }
    }
    @Test
//通过rowKey查询一条记录
    public void searchRecordByRk()throws  IOException{
        HTable table = (HTable) connection.getTable(TableName.valueOf("ns:tb_emp"));
       Get get=new Get(Bytes.toBytes("rk0099"));
        Result result = table.get(get);
        String rk = new String(result.getRow());
        int id = Integer.parseInt(new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("id"))));
        String name = new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("name")));
        int age = Integer.parseInt(new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("age"))));
        System.out.println(new Emp(rk,id,name,age));
    }
    @Test
    //得到特定单元格的值
    public void serachSpecialRecordByRk()throws  IOException{
        HTable table = (HTable) connection.getTable(TableName.valueOf("ns:tb_emp"));
        Get get=new Get(Bytes.toBytes("rk0099"));
    // get.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("name"));
        Result result = table.get(get);
        System.out.println(new String(result.getValue(Bytes.toBytes("cf"),Bytes.toBytes("name"))));
    }
    @After
    public void releaseResource() throws IOException {
        if (admin!=null){
            admin.close();
        }
        if (connection!=null){
            connection.close();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值