HBase Java API 练习

1 环境准备

1)成功搭建Hadoop-2.2.0开发环境
2)成功启动HBase,通过HBase Shell进行测试
3)使用MyEclipse作为开发工具
4)使用Maven构建项目

2 项目创建

2.1 创建Project

HBase-api-创建项目

由于我已经创建了项目,所以这里会报错,只要改下Artifact Id就可以。而你只需要输入没有使用过的Artifact Id。

HBase-api-创建项目2.png

2.2 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.szh</groupId>
  <artifactId>HBase</artifactId>
  <version>0.0.1</version>
  <packaging>jar</packaging>

  <name>HBase</name>
  <url>http://maven.apache.org</url>

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <hadoop.version>2.2.0</hadoop.version>
  </properties>

  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>${hadoop.version}</version>
        </dependency>
         <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>${hadoop.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>0.98.23-hadoop2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-common</artifactId>
            <version>0.98.23-hadoop2</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>0.98.23-hadoop2</version>
        </dependency>
        <dependency>  
            <groupId>jdk.tools</groupId>  
            <artifactId>jdk.tools</artifactId>  
            <version>1.7</version>  
            <scope>system</scope>  
            <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>  
        </dependency>  
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.1</version>
                <executions>
                    <!-- Run shade goal on package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <!-- add Main-Class to manifest file -->
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.szh.hbase.MyDriver</mainClass>
                                </transformer>
                            </transformers>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

在上面的pom.xml中我们导入了hadoop和hbase开发所需要的包,待会我们还要学习如何开发MapReduce和HBase的交互,所以先做好准备,使用Maven开发最好要保证网速,下载真的很慢!!!等待下载完毕....

2.3 MyHbase实例

使用Java API和使用HBase shell本质上是没有任何区别的,都是HBase里面的DDL操作,所以我们本次使用的例子跟HBase Shell 练习里面的例子是一样的,在这里我们先贴出局部代码,大家不用着急,最后会把项目代码给大家的。

1)创建HBaseConfiguration来获取HBase的配置文件信息

    static Configuration conf = null;
    static {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "szh");
    }

2)创建表格

     /**
     * 创建表格
     * @param tbName 表名
     * @param cf 列族名
     * @throws IOException 
     * @throws ZooKeeperConnectionException 
     * @throws MasterNotRunningException 
     */
    @SuppressWarnings({ "all" })
    public static void createTable(String tbName,String[] cf) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
        //用于执行操作
        HBaseAdmin admin = new HBaseAdmin(conf);
        HTableDescriptor desc = new HTableDescriptor(tbName);
        for(int i=0;i<cf.length;i++){
            desc.addFamily(new HColumnDescriptor(cf[i]));
        }
        //判断表格是否存在
        if(admin.tableExists(tbName)){
            System.out.println(tbName+" exists");
            System.exit(0);
        }else{
            admin.createTable(desc);
            System.out.println("create table success");
        }
    }

3)删除表格

public static void deleteTable(String tableName) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
        //用于执行操作
        HBaseAdmin admin = new HBaseAdmin(conf);
        HTableDescriptor desc = new HTableDescriptor(tableName);
        //判断表格是否存在
        if(admin.tableExists(tableName)){
            admin.disable(tableName);
            admin.drop(tableName);
            System.out.println("delete table success");
        }else{
            System.out.println("table is not exist");
        }
    }

4)插入数据

@SuppressWarnings("all")
    public static void add(String tableName,String rowKey,String family,String qualifier,String value) throws IOException{
        Put put = new Put(Bytes.toBytes(rowKey));
        HTable table = new HTable(conf, tableName);
        put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier), Bytes.toBytes(value));
        table.put(put);
        System.out.println("add data success");
        System.out.println("===========");
    }

执行main函数:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        String tablebName = "student";
        String rowKey = "xiaoming";
        String[] family = {"info","address","score"};
        try {
//          createTable(tablebName, family);
            add(tablebName,rowKey,family[0],"age","18");
            add(tablebName,rowKey,family[0],"birthday","1990-12-12");
            add(tablebName,rowKey,family[0],"school","beijingdaxue");
            add(tablebName,rowKey,family[1],"country","china");
            add(tablebName,rowKey,family[1],"province","guangdong");
            add(tablebName,rowKey,family[1],"city","shenzhen");
            add(tablebName,rowKey,family[1],"yuwen","99");
            add(tablebName,rowKey,family[1],"shuxue","98");
            add(tablebName,rowKey,family[1],"yingyu","100");
        } catch (MasterNotRunningException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ZooKeeperConnectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

使用HBase Shell查询结果,如下:

执行插入数据.png

5)删除数据

    public static void deleteAppointColumn(String tableName,String rowKey,String family,String qualifier) throws IOException{
        HTable table = new HTable(conf,Bytes.toBytes(tableName));
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        delete.deleteColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
        table.delete(delete);
        System.out.println("delete data success");
        System.out.println("===========");
    }

执行main函数:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String tablebName = "student";
        String rowKey = "xiaoming";
        String[] family = {"info","address","score"};
        try {
            deleteAppointColumn(tablebName,rowKey,family[1],"yuwen");
            deleteAppointColumn(tablebName,rowKey,family[1],"shuxue");
            deleteAppointColumn(tablebName,rowKey,family[1],"yingyu");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

使用 HBase Shell 查询结果,如下:

执行删除后结果.png

6)更新数据

    public static void update(String tableName,String rowKey,String family,String qualifier,String value) throws IOException{
        Put put = new Put(Bytes.toBytes(rowKey));
        HTable table = new HTable(conf, tableName);
        put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier), Bytes.toBytes(value));
        table.put(put);
        System.out.println("update data success");
        System.out.println("===========");
    }

执行main函数:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        String tablebName = "student";
        String rowKey = "xiaoming";
        String[] family = {"info","address","score"};
        try {
            update(tablebName,rowKey,family[0],"age","100");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

使用HBase Shell查询,结果如下:

执行更新结果.png

7)查询数据
7.1)全盘扫描

 public static void scanAll(String tableName,String startRow,String stopRow) throws IOException{
        
        HTable table = new HTable(conf, tableName);
        Scan scan = new Scan();
        scan.setStartRow(Bytes.toBytes(startRow));
        scan.setStopRow(Bytes.toBytes(stopRow));
        ResultScanner rs = null;
        try{
            System.out.println("全盘扫描");
            rs = table.getScanner(scan);
            for(Result r:rs){
                for(KeyValue kv:r.list()){
                    System.out.println("rowKey: "+ Bytes.toString(kv.getRow())
                            +" family: "+ Bytes.toString(kv.getFamily())
                            +" qualifiter: "+Bytes.toString(kv.getQualifier())
                            +" value "+Bytes.toString(kv.getValue())
                            );
                }
                
            }
            
        }finally{
            if(rs!=null){
                rs.close();
            }
        }
        System.out.println("===========");
    }

7.2)查询某一列族

public static void scanByFamily(String tableName,String startRow,String stopRow,String family) throws IOException{
        
        HTable table = new HTable(conf, tableName);
        Scan scan = new Scan();
        scan.setStartRow(Bytes.toBytes(startRow));
        scan.setStopRow(Bytes.toBytes(stopRow));
        scan.addFamily(Bytes.toBytes(family));
        ResultScanner rs = null;
        try{
            System.out.println("查询某一列族");
            rs = table.getScanner(scan);
            for(Result r:rs){
                for(KeyValue kv:r.list()){
                    System.out.println("rowKey: "+ Bytes.toString(kv.getRow())
                            +" family: "+ Bytes.toString(kv.getFamily())
                            +" qualifiter: "+Bytes.toString(kv.getQualifier())
                            +" value "+Bytes.toString(kv.getValue())
                            );
                }
                
            }
            
        }finally{
            if(rs!=null){
                rs.close();
            }
        }
        System.out.println("===========");
    }

7.3)查询某一列

public static void scanByColumns(String tableName,String startRow,String stopRow,String family,String qualifiter) throws IOException{
        
        HTable table = new HTable(conf, tableName);
        Scan scan = new Scan();
        scan.setStartRow(Bytes.toBytes(startRow));
        scan.setStopRow(Bytes.toBytes(stopRow));
        scan.addColumn(Bytes.toBytes(family),Bytes.toBytes(qualifiter));
        ResultScanner rs = null;
        try{
            System.out.println("查询某一列");
            rs = table.getScanner(scan);
            for(Result r:rs){
                for(KeyValue kv:r.list()){
                    System.out.println("rowKey: "+ Bytes.toString(kv.getRow())
                            +" family: "+ Bytes.toString(kv.getFamily())
                            +" qualifiter: "+Bytes.toString(kv.getQualifier())
                            +" value "+Bytes.toString(kv.getValue())
                            );
                }
                
            }
            
        }finally{
            if(rs!=null){
                rs.close();
            }
        }
        System.out.println("===========");
    }

7.4)查询某一列的多个版本

    public static void getByVersion(String tableName,String rowKey,String family,String qualifier) throws IOException{
        HTable table = new HTable(conf, Bytes.toBytes(tableName));  
        Get get = new Get(Bytes.toBytes(rowKey));   
        get.setMaxVersions(5);  
        Result result = table.get(get);
        System.out.println("查询某一列多版本");
        List<KeyValue> list = (List<KeyValue>) result.getColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
        for (KeyValue kv : list) {  
            System.out.println("rowKey: "+ Bytes.toString(kv.getRow())
                    +" family: "+ Bytes.toString(kv.getFamily())
                    +" qualifiter: "+Bytes.toString(kv.getQualifier())
                    +" value "+Bytes.toString(kv.getValue())
                    +" TimeStamp: "+kv.getTimestamp()
                    );
        }  
        System.out.println("===========");
    }

这里需要注意的是,0.98版本的HBase默认VERSIONS为1,所以如果你想要获取某一列多个版本数据的话,首先得去修改HBase该列所属的列族的VERSIONS,举个例子:

a. 进入HBase Shell
b. 输入一下命令

alter 'student',NAME=>'info',VERSIONS => 5

查询修改结果:

describe 'student'

更多HBase Shell细节 可查看HBase Shell 练习
7.5)查询某一行的数据

    public static void getByRowKey(String tableName,String rowKey) throws IOException{
        HTable table = new HTable(conf,Bytes.toBytes(tableName));
        Get get = new Get(Bytes.toBytes(rowKey));
        Result result = table.get(get);
         System.out.println("查询某一行");
        for (KeyValue kv : result.list()) {  
            System.out.println("rowKey: "+ Bytes.toString(kv.getRow())
                    +" family: "+ Bytes.toString(kv.getFamily())
                    +" qualifiter: "+Bytes.toString(kv.getQualifier())
                    +" value "+Bytes.toString(kv.getValue())
                    +" TimeStamp: "+kv.getTimestamp()
                    );
        }  
        System.out.println("===========");
    }

执行main函数:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String tablebName = "student";
        String rowKey = "xiaoming";
        String[] family = {"info","address","score"};
        try {
            scanAll(tablebName,rowKey,rowKey);
            scanByFamily(tablebName,rowKey,rowKey,family[0]);
            scanByColumns(tablebName,rowKey,rowKey,family[0],"age");
            getByVersion(tablebName,rowKey,family[0],"age");
            getByRowKey(tablebName,rowKey);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

查看Console:

五种查询结果.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容