hbase 总结

 hbase 的基本概念

  1. 表:HBase采用表来组织数据,表由行和列组成,列划分为若干个列族;
  2. 行:每个HBase表都由若干行组成,每个行由行键(row key)来标识;
  3. 列族:一个HBase表被分组成许多“列族”(Column Family)的集合,它是基本的访问控制单元,创建表的时候创建;
  4. 列限定符:列族里的数据通过列限定符(或列)来定位;
  5. 单元格:在HBase表中,通过行、列族和列限定符确定一个“单元格”(cell);
  6. 时间戳:每个单元格都保存着同一份数据的多个版本,这些版本采用时间戳进行索引;

hbase-site.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>hbase.rootdir</name>
        <value>hdfs://mycluster/hbase</value>
    </property>
    <property>
        <name>hbase.cluster.distributed</name>
        <value>true</value>
    </property>
    <property>
        <name>hbase.zookeeper.quorum</name>
        <value>xiemeng-01,xiemeng-02,xiemeng-03,xiemeng-04</value>
    </property>
    <property>
        <name>hbase.zookeeper.property.dataDir</name>
        <value>/home/xiemeng/software/hadoop-3.2.0/app/apache-zookeeper-3.5.8-bin/data</value>
    </property>
    <property>
        <name>hbase.tmp.dir</name>
        <value>/home/xiemeng/software/hbase-2.2.6/tmp</value>
    </property>
</configuration>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>${hbase.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>${hbase.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-common</artifactId>
            <version>${hbase.version}</version>
        </dependency>
class StudentBean {

    private  Integer studentNo;

    private  String name;

    private  String studentName;

    private Integer studentAge;

}

/**
 * HBabse 测试类
 */
public class HBaseTest {
    /**
     * 获取连接对象
     * @return
     * @throws IOException
     */
    private static  Connection connection = null;

    /**
     * 日志类
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(HBaseTest.class);

    /**
     * 获取连接
     * @return
     * @throws IOException
     */
    public static Connection getConnection() throws IOException {
        Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.property.clientPort","2181");
        configuration.set("hbase.zookeeper.quorum","192.168.64.128,192.168.64.130,192.168.64.131,192.168.64.133");
        configuration.set("hbase.master","192.168.64.128:16010");
        synchronized(HBaseTest.class){
            if(null==connection){
              connection = ConnectionFactory.createConnection(configuration);
            }
        }

        return  connection;
    }

    /**
     * 创建表
     * @param tableName
     * @param cols
     * @throws IOException
     */
    public static void createTable(String tableName,String [] cols) throws IOException {
        TableName name = TableName.valueOf(tableName);
        Admin admin = getConnection().getAdmin();
        if(admin.tableExists(name)){
            System.out.println("表已经存在");
        }else {
            TableDescriptorBuilder.ModifyableTableDescriptor descriptor = (TableDescriptorBuilder.ModifyableTableDescriptor) TableDescriptorBuilder.newBuilder(TableName.valueOf(tableName)).build();
            for(String col: cols){
                ColumnFamilyDescriptor columnDescriptor = ColumnFamilyDescriptorBuilder.newBuilder(col.getBytes()).build();
                descriptor.setColumnFamily(columnDescriptor);
            }
            admin.createTable(descriptor);
        }
    }

    /**
     * 插入数据
     * @param tableName
     * @param student
     * @throws IOException
     */
    public static  void  insert(String tableName, StudentBean student) throws IOException {
        Table table = getConnection().getTable(TableName.valueOf(tableName));
        Put put = new Put(("stu"+student.getStudentNo()).getBytes());
        put.addColumn("stu_name".getBytes(),"student_name".getBytes(),student.getStudentName().getBytes());
        put.addColumn("stu_name".getBytes(),"name".getBytes(),student.getStudentName().getBytes());
        put.addColumn("stu_age".getBytes(),"student_age".getBytes(),(""+student.getStudentAge()).getBytes());
        table.put(put);
    }

    public static List<String> getColumnFamilyNames(String tableName) throws IOException {
        Table table = getConnection().getTable(TableName.valueOf(tableName));
        TableDescriptor tableDescriptor = table.getDescriptor();
        List<String> columnFamilyNames = new ArrayList<>();
        for(ColumnFamilyDescriptor columnFamilyDescriptor :tableDescriptor.getColumnFamilies()){
            columnFamilyNames.add(columnFamilyDescriptor.getNameAsString());
        }
        return columnFamilyNames;
    }

    public static Set<String> getFamilyNames(String tableName) throws IOException {
        Table table = getConnection().getTable(TableName.valueOf(tableName));
        TableDescriptor descriptor = table.getDescriptor();
        Set<byte[]> familySet = descriptor.getColumnFamilyNames();
        Set<String> familyNameSet = familySet.stream().map(byteValue -> Bytes.toString(byteValue)).collect(Collectors.toSet());
        return familyNameSet;
    }

    public static List<StudentBean> getAllData(String tableName) throws IOException {
        Table descriptor = getConnection().getTable(TableName.valueOf(tableName));
        Scan scan = new Scan();
        scan.setStartRow("stu1".getBytes());
        scan.setStopRow("stu1000".getBytes());
        scan.addColumn("stu_name".getBytes(),"student_name".getBytes());
        ResultScanner results = descriptor.getScanner(scan);
        List<StudentBean> studentBeans = new ArrayList<>();
        for(Result result: results){
            if(!result.isEmpty()){
                StudentBean studentBean = new StudentBean();
                String rowKey = new String(result.getRow());
                int studentNo = Integer.parseInt(rowKey.substring(3));
                studentBean.setStudentNo(studentNo);
                for(Cell cell: result.rawCells()){
                    String name = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
                    String value = Bytes.toString(cell.getValueArray(),cell.getValueOffset(),cell.getValueLength());
                    if(name.equals("student_name")){
                        studentBean.setStudentName(value);
                    }
                    if(name.equals("student_age")){
                        studentBean.setStudentAge(Integer.parseInt(value));
                    }

                    if(name.equals("name")){
                        studentBean.setName(value);
                    }
                }
               studentBeans.add(studentBean);
            }
        }
        return studentBeans;
    }

    public static StudentBean getRowByRowKey(String tableName,Integer rowKey) throws IOException {
        StudentBean studentBean = new StudentBean();
        studentBean.setStudentNo(rowKey);
        Get get = new Get(("stu"+rowKey).getBytes());
        Table table = getConnection().getTable(TableName.valueOf(tableName));
        if(!get.isCheckExistenceOnly()){
            Result result = table.get(get);
            for(Cell cell: result.rawCells()){
                String name = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
                String value = Bytes.toString(cell.getValueArray(),cell.getValueOffset(),cell.getValueLength());
                if(name.equals("student_name")){
                    studentBean.setStudentName(value);
                }

                if(name.equals("student_age")){
                    studentBean.setStudentAge(Integer.parseInt(value));
                }
            }
        }
        return studentBean;
    }

    public static void updateTable(String tableName) throws IOException {
        HTable table = (HTable)getConnection().getTable(TableName.valueOf(tableName));
        Put put = new Put("stu-1".getBytes());
        put.addColumn("stu_name".getBytes(),"name".getBytes(),UUID.randomUUID().toString().getBytes());
        table.put(put);
        table.clearRegionCache();
    }

    public void deteleTable(String tableName) throws IOException {
        Table table = getConnection().getTable(TableName.valueOf(tableName));

    }
    public static void main(String[] args) throws IOException {
        String [] cols = new String [] {"stu_no","stu_name","stu_age"};
        //createTable("student",cols);
        long begin = System.currentTimeMillis();
        /*for(int i=1;i<100;i++){
          StudentBean student = new StudentBean(i, UUID.randomUUID().toString(), RandomUtils.nextInt());
          putData("student",student);
        }*/

        long end = System.currentTimeMillis();
        System.out.println(String.format("插入数据时长%d",(end-begin)));
        //StudentBean studentBean = getRowByRowKey("student",1);
        //LOGGER.info(studentBean.toString());
        updateTable("student");
        List<StudentBean> studentBeans = getAllData("student");
        //studentBeans.stream().forEach(System.out::println);
       //createTable("student2",cols);
       //getColumnFamilyNames("student").forEach(System.out::println);
       //System.out.println("获取所有列簇==========================================");
       //getFamilyNames("student").forEach(System.out::println);

    }
}


hbase 的表设计原则

微信朋友圈实现

分布式数据库 HBase(详解) - 知乎 (zhihu.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值