HBase安装及操作

本文介绍了如何在单机和集群环境中安装HBase,包括内嵌Zookeeper的单机版配置,以及高可用集群的设置步骤。详细讲述了配置hbase-site.xml和hbase-env.sh文件,启动HBase、HDFS以及Zookeeper的过程,并演示了HBase shell的基本操作,如创建命名空间、region,插入数据以及查看表结构等。

单机版: (hbase内嵌有zookeeper)
解压hbase软件,到达conf目录下
配置hbase-site.xml文件

<configuration>
  <property>
    <name>hbase.rootdir</name>    配置hbase存在位置
    <value>file:///home/testuser/hbase</value>
  </property>
  <property>
    <name>hbase.zookeeper.property.dataDir</name>  配置hbase文件保存路径
    <value>/home/testuser/zookeeper</value>
  </property>
</configuration>

配置hbase-env.sh文件:把29行的注释取消,配置虚拟机上面的Java地址

     28 # The java implementation to use.  Java 1.6 required.
     29 export JAVA_HOME=/usr/java/default        
     30 
     31 # Extra Java CLASSPATH elements.  Optional.
     32 # export HBASE_CLASSPATH

然后使用start-hbase.sh命令启动hbase
使用hbase shell 进入hbase的命令提示界面,进行hbase语句操作练习

hbase集群:(高可用)
配置hbase-site.xml文件

<configuration>
<property>
    <name>hbase.rootdir</name>
    <value>hdfs://bx/hbase</value>    此处的bx为以前搭建hdfs集群时,使用的那个集群代号
</property>
<property>
  <name>hbase.zookeeper.quorum</name>       指定集群的几台zookeeper主机名
  <value>CentOS8,CentOS9,CentOS10,CentOS15</value>
</property>
<property>
  <name>hbase.cluster.distributed</name>    设置使用zookeeper集群,true为使用
  <value>true</value>
</property>
</configuration>

配置hbase-env.sh文件:把124行的注释取消,把true改为false,代表不使用自带的zookeeper

121 # export HBASE_SLAVE_SLEEP=0.1
    122 #
    123 # Tell HBase whether it should manage it's own instance of Zookeeper or not.
    124 export HBASE_MANAGES_ZK=false      默认为true
    125 #

设置regionservers文件
vi regionservers

     CentOS8    设置四个regionserver节点
     CentOS9
     CentOS10
     CentOS15

创建backup-masters文件
vi backup-masters

CentOS8    指定两台master主机
CentOS9  

然后再把hadoop2.6.5/etc/hadoop/hdfs-site.xml文件拷贝到该目录下

到此,配置文件准备完毕。
首先每台机器启动zkServer.start.sh
然后在配了免密钥登录的机器上执行start-dfs.sh ,启动hdfs集群
最后,在start-hbase.sh 启动hbase数据库


安装完毕后就开始可以使用了

创建命名空间:

create_namespace   'benxi'

创建region:

create 't_user','f1',f2' 

插入数据:

put 't_user','001','f1:name','张三'    第一个为表名,第二个为Row Key,第三个为列族名:属性名,第四个为属性的value
put 't_user','001','f1:age','13'

查看表结构:desc 't_user' 显示结果如下:(部分参数解释)

Table t_user is ENABLED
t_user
COLUMN FAMILIES DESCRIPTION
{NAME=>’f1’, 列族名
DATA_BLOCK_ENCODING=>’NONE’,
BLOOMFILTER=>’ROW’,
REPLICATION_SCOPE => ‘0’,
VERSIONS => ‘1’, 最大保存数为1
COMPRESSION => ‘NONE’,
MIN_VERSIONS => ‘0’, 最小保存数为0
TTL=>FOREVER’, 保存时间为永久有效
KEEP_DELETED_CELLS => ‘FALSE’,
BLOCKSIZE=>’65536’, 一个块大小,单位字节,64k
IN_MEMORY=>’false’,
BLOCKCACHE => ‘true’} 默认为true,开启查询保存

禁用命名空间

disabled ‘t_user’

删除命名空间 首先要禁用表才能删除。

 drop  't_user'

接下来使用Java代码进行操作:

public class create_test1 {
    /**
     * 案例1:
     * 存放电信通话数据
     * 表:t_phone_recode   --> t_cdr
     * rowkey:phone+Long.maxvalue-date
     * 列族:cf1:
     */
    String tableName = "t_phone_recode";
    Random r = new Random();
    @Test
    public void createTable() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表的对象
        HBaseAdmin admin = new HBaseAdmin(config);

        //判断该表是否存在
        if(admin.tableExists(tableName)){
            //使表失效,然后才能进行删除操作
            admin.disableTable(tableName);
            //删除表操作
            admin.deleteTable(tableName);
        }
        //创建一个表对象
        HTableDescriptor table = new HTableDescriptor(TableName.valueOf(tableName));
        //创建列族,需要创建多个列族,就多写几个
        HColumnDescriptor columnfamily = new HColumnDescriptor("cf1");
        //设置列族的最大cell保存数量(默认为2),和设置列族最小保存数量(默认为0)
        columnfamily.setMaxVersions(2);
        columnfamily.setMinVersions(1);
        //把列族设置添加进表中
        table.addFamily(columnfamily);
        //把表对象添加到HBaseAdmin对象中去
        admin.createTable(table);
        //关闭连接
        admin.close();
    }
    /**
     * 列族里面的列:当前手机号,目标手机号,通话类型,通话时间
     */
    @Test
    public void insertDates() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        for(int i = 0;i<100;i++){
            //随机生成一个手机号
            String phone = getPhone("151");
            //创建put集合对象
            List<Put> puts = new ArrayList<Put>();
            for(int j = 0;j<10;j++){
                //随机生成一个日期,虽然生成的可能不准确,可能会出现20190230这样的日期
                String date  = getDate("2019");
                //把手机号和日期拼接在一起作为rowkey
                String rowkey = phone + "_"+(Long.MAX_VALUE-Long.parseLong(date));
                //put对象用来进行对HBase操作
                Put put = new Put(rowkey.getBytes());
                //把rowkey放到Put对象中去
                put.add("cf1".getBytes(),"phone".getBytes(),phone.getBytes());
                put.add("cf1".getBytes(),"dest".getBytes(),getPhone("151").getBytes());
                put.add("cf1".getBytes(),"type".getBytes(),(r.nextInt(2)+"").getBytes());
                put.add("cf1".getBytes(),"date".getBytes(),date.getBytes());
                //把put对象添加到集合中
                puts.add(put);
            }
            //把生成的put对象放到HTable对象中去
            table.put(puts);
        }
        table.close();
    }
    /**
     * 已知rowkey查询一行数据
     * @throws Exception
     */
    @Test
    public void findOne() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        String rowkey = "15198932957_9223351846730721367";
        //通过Get获取rowkey为15198518559_9223351846450735的对象
        Get get = new Get(rowkey.getBytes());
//设置访问拦截后,设置这个继续访问
        get.setAttribute("user", "zs".getBytes());
        //把rowkey关联表,Result对象代表hbase中一行数据
        Result re = table.get(get);
//      byte[] value = re.getValue("cf1".getBytes(), "dest".getBytes());
//      System.out.println(new String(value));
        //获取最高版本的,最新的那条数据。获取一个单元格
        Cell destCell=re.getColumnLatestCell("cf1".getBytes(), "dest".getBytes());
        String dest = new String(CellUtil.cloneValue(destCell));
        String type = new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(),"dest".getBytes())));

        System.out.println("目标手机号:"+dest);
        System.out.println("通话类型:"+(type.equals("1")?"主叫":"被叫"));

    }
    /**
     * 查询一个手机号15198518559第二个季度的所有通话记录
     */
    @Test
    public void findRowsTwo() throws Exception{
        Configuration config = new Configuration();
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        HTable table = new HTable(config, tableName);
        //使用正则匹配条件,^15198932957_表示以15198932957_开头的rowkey; $1234表示匹配以1234结尾的rowkey
        RowFilter rf = new RowFilter(CompareOp.EQUAL, new RegexStringComparator("^15198932957_") );
        //使用Scan查询多条数据
        Scan scan = new Scan();
        scan.setFilter(rf);
        //使用ResultScanner对象获取表中所有数据
        ResultScanner res = table.getScanner(scan);
        for (Result result : res) {
            System.out.println(new String(CellUtil.cloneValue(result.getColumnLatestCell("cf1".getBytes(),"dest".getBytes()))));
            System.out.println(new String(CellUtil.cloneValue(result.getColumnLatestCell("cf1".getBytes(),"phone".getBytes()))));
            System.out.println(new String(CellUtil.cloneValue(result.getColumnLatestCell("cf1".getBytes(),"date".getBytes()))));
            System.out.println("-----------------");
        }

    }
    @Test
    public void findRows() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        //使用Scan对象查询多个数据
        Scan scan = new Scan();
        String startRowkey ="15195946934_"+(Long.MAX_VALUE-20190630246060l);
        String endRowkey ="15195946934_"+(Long.MAX_VALUE-20190331246060l);
        scan.setStartRow(startRowkey.getBytes());
        scan.setStopRow(endRowkey.getBytes());

        ResultScanner res =table.getScanner(scan);
        for(Result re :res){
            Cell destCell=re.getColumnLatestCell("cf1".getBytes(), "dest".getBytes());//获取一行里面的其中一个单元格
            String dest =new String(CellUtil.cloneValue(destCell));
            String type =new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(), "type".getBytes())));
            String date =new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(), "date".getBytes())));
            String phone =new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(), "phone".getBytes())));
            System.out.println("通话时间:"+date);
            System.out.println("目标手机号"+dest);
            System.out.println("通话类型:"+(type.equals("1")?"主叫":"被叫"));
            System.out.println("-------------------------------");
        }
        table.close();
    }
    /**
     * 查询手机号13899154250,的所有主叫记录
     */
    @Test
    public void findRows2()throws Exception{
        Configuration config =new Configuration();
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        HTable htable  =new HTable(config, tableName);

        PrefixFilter rowkeyPrefix =new PrefixFilter("15198932957".getBytes());
        SingleColumnValueFilter f2 =new SingleColumnValueFilter("cf1".getBytes(), "type".getBytes(), CompareOp.EQUAL, "1".getBytes());//判断一个列的值是否等于(大于,小于等)某个指定的value
        FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
        list.addFilter(rowkeyPrefix);
        list.addFilter(f2);
        Scan scan =new Scan();
        scan.setFilter(list);

        ResultScanner res =htable.getScanner(scan);
        for(Result re :res){
            Cell destCell=re.getColumnLatestCell("cf1".getBytes(), "dest".getBytes());//获取一行里面的其中一个单元格
            String dest =new String(CellUtil.cloneValue(destCell));
            String type =new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(), "type".getBytes())));
            String date =new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(), "date".getBytes())));
            String phone =new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(), "phone".getBytes())));
            System.out.println("通话时间:"+date);
            System.out.println("目标手机号"+dest);
            System.out.println("通话类型:"+(type.equals("1")?"主叫":"被叫"));
            System.out.println("-------------------------------");
        }
        htable.close();
    }
    @Test
    public void findRowTwo2() throws Exception{
        Configuration config = new Configuration();
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        HTable htable  =new HTable(config, tableName);

        //设置查询条件,因为条件比较多,使用过滤器集合对象存储FilterList,MUST_PASS_ALL 设置多个条件,MUST_PASS_ONE 设置一个条件
        FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
        //判断一个列的值是否等于(大于,小于等)某个指定的value。 第一个指定列族,第二个参数指定属性名,第三个指定比较方式(EQUAL为相等),第四个参数代表比较对比的值
        SingleColumnValueFilter f1 = new SingleColumnValueFilter("cf1".getBytes(), "type".getBytes(), CompareOp.EQUAL, "1".getBytes());
        //设置前缀过滤器,查询rowkey为15198932957的所有数据
        PrefixFilter rowkeyPrefix = new PrefixFilter("15198932957".getBytes());
        //把过滤条件添加进入list集合中
        list.addFilter(f1);
        list.addFilter(rowkeyPrefix);
        //使用Scan查询多条数据
        Scan scan = new Scan();
        //给scan对象设置过滤器,可以设置一条,也可以是一个集合
        scan.setFilter(list);
        //把使用迭代器
        ResultScanner res = htable.getScanner(scan);
        for (Result result : res) {
            System.out.println("通话时间:"+new String(CellUtil.cloneValue(result.getColumnLatestCell("cf1".getBytes(),"date".getBytes()))));
            System.out.println("当前手机号:"+new String(CellUtil.cloneValue(result.getColumnLatestCell("cf1".getBytes(),"phone".getBytes()))));
            System.out.println("目标手机号:"+new String(CellUtil.cloneValue(result.getColumnLatestCell("cf1".getBytes(),"dest".getBytes()))));
            System.out.println("电话类型:"+((new String(CellUtil.cloneValue(result.getColumnLatestCell("cf1".getBytes(),"type".getBytes())))).equals("1")?"主叫":"被叫"));
        }
        htable.close();

    }
    //修改某个单元格的内容
    @Test
    public void update()throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        //把手机号和日期拼接在一起作为rowkey
        String rowkey = "15198932957_9223351846730721367";
        //put对象用来进行对HBase操作
        Put put = new Put(rowkey.getBytes());
        //把rowkey放到Put对象中去
        put.add("cf1".getBytes(),"dest".getBytes(),getPhone("151").getBytes());
        put.add("cf1".getBytes(),"type".getBytes(),(r.nextInt(2)+"").getBytes());
        put.add("cf1".getBytes(),"date".getBytes(),getDate("2017").getBytes());
        table.put(put);
        table.close();
    }
    //删除一个指定column(所有版本)
    @Test
    public void delete2() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        String rowkey = "15198932957_9223351846240714672";
        //创建Delete对象,把rowkey传递过去
        Delete del = new Delete(rowkey.getBytes());
        //删除最新的符合条件的数据
        Delete delete = del.deleteColumn("cf1".getBytes(), "dest".getBytes());
        table.delete(delete);
        table.close();
    }
    @Test
    public void delete() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        //把手机号和日期拼接在一起作为rowkey
        String rowkey = "15198932957_9223351846240714672";
        //通过Get获取rowkey为15198518559_9223351846450735的对象
        Get get = new Get(rowkey.getBytes());
        //把rowkey关联表,Result对象代表hbase中一行数据
        Result re = table.get(get);
//      byte[] value = re.getValue("cf1".getBytes(), "dest".getBytes());
//      System.out.println(new String(value));
        //获取最高版本的,最新的那条数据。获取一个单元格
//      Cell cell=re.getColumnLatestCell("cf1".getBytes(), "dest".getBytes());
//      Cell ce = CellUtil.createCell();
        Delete del = new Delete(rowkey.getBytes());
        del.deleteColumn("cf1".getBytes(), "dest".getBytes());
//      del.addDeleteMarker(cell);
        table.delete(del);
        table.close();
    }
    //删除指定的一行数据
    @Test
    public void deleteRowkey() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        String rowkey = "15198932957_9223351846240714672";
        //创建Delete对象,把rowkey传递过去
        Delete del = new Delete(rowkey.getBytes());
        //删除最新的符合条件的数据
//      Delete delete = del.deleteColumn("cf1".getBytes(), "dest".getBytes());
        table.delete(del);
        table.close();
    }
    //删除13899154250第3季度的通话记录
    @Test
    public void deleteByPhone() throws Exception{
        Configuration config = new Configuration();
        //指定zookeeper集群,和hbase-size.xml文件一样
        config.set("hbase.zookeeper.quorum", "CentOS8,CentOS9,CentOS10,CentOS15");
        //创建表操作对象,前面一个为configuration对象,后面为表名
        HTable table = new HTable(config, tableName);
        Scan scan = new Scan();
        //获得第三季度,long的最大值减去季度最大日期,得到起始日期
        String startdate = "15198902068_"+(Long.MAX_VALUE-20190930246060l);
        String lastdate = "15198902068_"+(Long.MAX_VALUE-20190630246060l);
        //把起始时间戳设置进Scan
        scan.setStartRow(startdate.getBytes());
        scan.setStopRow(lastdate.getBytes());
//      Delete del = new Delete("".getBytes());
        //往table对象中添加scan条件设置,创建ResultScanner对象,获取当前表的所有数据
        ResultScanner res =table.getScanner(scan);
        //遍历该表
        for(Result re :res){
            //获取一行里面的其中一个单元格
            Cell destCell=re.getColumnLatestCell("cf1".getBytes(), "dest".getBytes());
            //获取这列数据的rowkey,得到的是内存地址。一般不使用
            String str = re.getRow().toString();
            System.out.println(str);
            //取出当前单元格的电话号码所属
            String phone =new String(CellUtil.cloneValue(re.getColumnLatestCell("cf1".getBytes(), "phone".getBytes())));
            //如果当前电话号码为15198902068,则删除这个数据
            if("15198902068".equals(phone)){
                //设置删除条件
                Delete del = new Delete(re.getRow());
                //删除数据
                table.delete(del);
                continue;
            }
        }
        table.close();
    }
    //生成随机电话号码,传入前三位数,后面八位数随机生成
    private String getPhone(String prefix){
        return prefix+String.format("%08d", r.nextInt(99999999));
    }
    //随机生成日期,年份需要传入,月日时分秒随机生成
    private String getDate(String year){
        return year+String.format("%02d%02d%02d%02d%02d", new Object[]{r.nextInt(12)+1,r.nextInt(31)+1,r.nextInt(24),r.nextInt(60),r.nextInt(60)});
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值