package test;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
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.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;

import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTableInterface;

public class HBaseCommons {
 
    //声明静态配置
    static Configuration conf=null;
    static HConnection conn=null;
    static{
        conf=HBaseConfiguration.create();
    //    conf.set("hbase.zookeeper.quorum","Master.Hadoop");
        try {
            conn=HConnectionManager.createConnection(conf);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /*
     * 创建表
     *
     * @tableName 表名
     *
     * @family 列簇列表
     */
        public static void createTable(String tableName,String[] family)
             throws Exception{
         HBaseAdmin admin=new HBaseAdmin(conf);
         HTableDescriptor desc=new HTableDescriptor(TableName.valueOf(tableName));//新的语法
         for(int i=0;i<family.length;i++)
         {
             desc.addFamily(new HColumnDescriptor(family[i]));
         }
         if(admin.tableExists(tableName))
         {
             System.out.println("table Exists!");
             System.exit(0);
         } else{
             admin.createTable(desc);
             System.out.println("create table Sucess!");
         }
        }
    
    /*
     * 为表添加数据(适合知道有多少列簇的固定表)
     *
     * @rowKey rowKey
     *
     * @tableName 表名
     *
     * @column1 第一个列簇列表
     *
     * @value1 第一个列的值的列表
     *
     * @column2 第二个列簇列表
     *
     * @value2 第二个列的值的列表
     */
        public static void addData(String rowKey, String tableName, String[] column1,
                String[] value1, String[] column2, String[] value2)throws IOException{
            Put put=new Put(Bytes.toBytes(rowKey)); //设置rowKey
            HTableInterface table=conn.getTable(tableName); //获取表
            HColumnDescriptor[] columnFamilies=table.getTableDescriptor().getColumnFamilies();//获取所有的列簇
            for(int i=0;i<columnFamilies.length;i++){
                String familyName=columnFamilies[i].getNameAsString();//获取列簇名
                if(familyName.equals("article")){ //article列簇put数据
                    for(int j=0;j<column1.length;j++){
                        put.add(Bytes.toBytes(familyName),
                                   Bytes.toBytes(column1[j]),
                                   Bytes.toBytes(value1[j])
                                );                        
                      }
                  }
                if(familyName.equals("author")){ //article列簇put数据
                    for(int j=0;j<column2.length;j++){
                        put.add(Bytes.toBytes(familyName),
                                   Bytes.toBytes(column2[j]),
                                   Bytes.toBytes(value2[j])
                                );                        
                      }
                  }
            }
            table.put(put);
            table.close();
            System.out.println("add data Sucess!");
             
        }
        
        /*
         * 根据rowkey查询
         *
         * @rowKey rowKey
         *
         * @tableName 表名
         */
        
        public static Result getResult(String tableName,String rowKey)
        throws IOException{
            Get get=new Get(Bytes.toBytes(rowKey));
            HTableInterface table=conn.getTable(tableName); //获取表
            Result result=table.get(get);
            for(Cell kv:result.rawCells())
            {
                System.out.println("family:"+new String(CellUtil.cloneFamily(kv)));
                System.out.println("qualifier:"+new String(CellUtil.cloneQualifier(kv)));
                System.out.println("value:"+new String(CellUtil.cloneValue(kv)));
                System.out.println("Timestamp:"+kv.getTimestamp());
                System.out.println("------------------------------------------");
            /*    System.out.println("value:"+new String(CellUtil.cloneValue(kv)));*/
            }
            table.close();
            return result;
        }
        
        /*
         * 遍历查询hbase表
         *
         *  @tableName表名
         */
        public static void getResultScan(String tableName)throws IOException{
            Scan scan=new Scan();
            ResultScanner rs=null;
        //    HTable table=(HTable)tablePool.getTable(tableName);
            HTableInterface table=conn.getTable(tableName);
    //        Configuration hbaseConf=HBaseConfiguration.create();
    //        HTable table=new HTable(hbaseConf,tableName);
            try {
                rs=table.getScanner(scan);
                for(Result r:rs)
                {
                    for(Cell kv:r.rawCells())
                    {
                        System.out.println("family:"+new String(CellUtil.cloneFamily(kv)));
                        System.out.println("qualifier:"+new String(CellUtil.cloneQualifier(kv)));
                        System.out.println("value:"+new String(CellUtil.cloneValue(kv)));
                        System.out.println("Timestamp:"+kv.getTimestamp());
                        System.out.println("------------------------------------------");
                    /*    System.out.println("value:"+new String(CellUtil.cloneValue(kv)));*/
                    }
                }
            } catch (Exception e) {
                // TODO: handle exception
            }finally{
                rs.close();
                table.close();
            }
        }
    
    /*
     * 查询表中的某一列
     *
     * @tableName 表名
     *
     * @rowKey rowKey
     *
     * @familyName 列簇
     *
     * @columnName 列名
     */
        public static void getResultByColumn(String tableName,String rowKey,
                String familyName,String columnName)throws IOException{
          HTableInterface table=conn.getTable(tableName);
            Get get=new Get(Bytes.toBytes(rowKey));
            //获取指定列簇和列修饰符对应的列
            get.addColumn(Bytes.toBytes(familyName),Bytes.toBytes(columnName));
            Result result=table.get(get);
            for(Cell kv:result.rawCells())
            {
                System.out.println("family:"+new String(CellUtil.cloneFamily(kv)));
                System.out.println("qualifier:"+new String(CellUtil.cloneQualifier(kv)));
                System.out.println("value:"+new String(CellUtil.cloneValue(kv)));
                System.out.println("Timestamp:"+kv.getTimestamp());
                System.out.println("------------------------------------------");
            /*    System.out.println("value:"+new String(CellUtil.cloneValue(kv)));*/
            }
            table.close();
            
        }
            /*
             * 更新表中的某一列
             *
             * @tableName 表名
             *
             * @rowKey rowKey
             *
             * @familyName 列簇名
             *
             * @columnName 列名
             *
             * @value 更新后的值
             */
            public static void updateTable(String tableName,String rowKey,
                    String familyName,String columnName,String value)
            throws IOException{
                HTableInterface table=conn.getTable(tableName);
                Put put=new Put(Bytes.toBytes(rowKey));
                put.add(Bytes.toBytes(familyName),Bytes.toBytes(columnName),
                        Bytes.toBytes(value));
                table.put(put);
                table.close();
                System.out.println("update table Success!");
            }
            /*
             * 查询某列数据的多个版本
             *
             * @tableName 表名
             *
             * @rowKey rowKey
             *
             * @familyName 列簇名
             *
             * @columnName 列名
             */
            public static void getResultByVersion(String tableName,String rowKey,
                    String familyName,String columnName)throws IOException{
                HTableInterface table=conn.getTable(tableName);
                Get get=new Get(Bytes.toBytes(rowKey));
                get.addColumn(Bytes.toBytes(familyName),Bytes.toBytes(columnName));
                get.setMaxVersions(5);
                Result result=table.get(get);
                for(Cell kv:result.rawCells())
                {
                    System.out.println("family:"+new String(CellUtil.cloneFamily(kv)));
                    System.out.println("qualifier:"+new String(CellUtil.cloneQualifier(kv)));
                    System.out.println("value:"+new String(CellUtil.cloneValue(kv)));
                    System.out.println("Timestamp:"+kv.getTimestamp());
                    System.out.println("------------------------------------------");
                }
                table.close();
            }
            /*
             * 删除指定的列
             *
            *  @tableName 表名
             *
             *  @rowKey rowKey
             *  
             *  @familyName 列簇名
             *  
             *  @columnName 列名
             */
            public static void deleteColumn(String tableName,String rowKey,
                    String familyName,String columnName)throws IOException{
                HTableInterface table=conn.getTable(tableName);
                Delete deleteColumn=new Delete(Bytes.toBytes(rowKey));
                deleteColumn.deleteColumns(Bytes.toBytes(familyName),Bytes.toBytes(columnName));
                table.delete(deleteColumn);
                table.close();
                System.out.println(familyName+":"+columnName+"is deleted!");
            }
            /*
             * 删除指定的列
             *
             * @tableName 表名
             *
             * @rowKey rowKey
             */
            public static void deleteAllColumn(String tableName,String rowKey)
            throws IOException{
                HTableInterface table=conn.getTable(tableName);
                Delete deleteAll=new Delete(Bytes.toBytes(rowKey));
                table.delete(deleteAll);
                table.close();
                System.out.println("all columns are deleted!");                
            }
            
            /*
             * 删除表
             *
             * @tableName 表名
             */
            public static void deleteTable(String tableName)throws IOException{
                HBaseAdmin admin=new HBaseAdmin(conf);
                admin.disableTable(tableName);
                admin.deleteTable(tableName);
                System.out.println(tableName+" is deleted!");
            }
            
            public static void main(String[] args) throws Exception{
                getResultScan("Movie");
                getResult("Movie","7065187");
            }
}

做个小推广:程序员经常久坐,颈椎毛病比较多,特别推荐ventry颈椎保健枕

HBase(0.96)新的Java API操作的更多相关文章

  1. HBase 6、用Phoenix Java api操作HBase

    开发环境准备:eclipse3.5.jdk1.7.window8.hadoop2.2.0.hbase0.98.0.2.phoenix4.3.0 1.从集群拷贝以下文件:core-site.xml.hb ...

  2. hadoop2-HBase的Java API操作

    Hbase提供了丰富的Java API,以及线程池操作,下面我用线程池来展示一下使用Java API操作Hbase. 项目结构如下: 我使用的Hbase的版本是 hbase-0.98.9-hadoop ...

  3. java api操作

    java api操作 导入开发包 将hbase安装包中lib下包导入java项目   创建表   Configuration conf = HBaseConfiguration.create(); c ...

  4. hive-通过Java API操作

    通过Java API操作hive,算是测试hive第三种对外接口 测试hive 服务启动 package org.admln.hive; import java.sql.SQLException; i ...

  5. 使用Java API操作HDFS文件系统

    使用Junit封装HFDS import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org ...

  6. Kafka系列三 java API操作

    使用java API操作kafka 1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs ...

  7. Hadoop 2.2 & HBase 0.96 Maven 依赖总结

    由于Hbase 0.94对Hadoop 2.x的支持不是非常好,故直接添加Hbase 0.94的jar依赖可能会导致问题. 但是直接添加Hbase0.96的依赖,由于官方并没有发布Hbase 0.96 ...

  8. MongoDB Java API操作很全的整理

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,一般生产上建议以共享分片的形式来部署. 但是MongoDB官方也提供了其它语言的客户端操作API.如下图所示: 提供了C.C++ ...

  9. zookeeper的java api操作

    zookeeper的java api操作 创建会话: Zookeeper(String connectString,int sessionTimeout,Watcher watcher) Zookee ...

随机推荐

  1. javaEE框架获取和传参要使用的类和接口

    1:spring  2:struts2获取前台数据(action中获取) //4修改用户密码. public String updateUserPassword() throws Exception{ ...

  2. MSXML2.XMLHTTP.4.0对象

    一.使用步骤:1.创建XMLHTTP对象 //需MSXML4.0支持2.打开与服务端的连接,同时定义指令发送方式,服务网页(URL)和请求权限等.客户端通过Open命令打开与服务端的服务网页的连接.与 ...

  3. 月薪5K和月薪50K的程序员,差距都在哪里?

    毕业两年买房买车,BAT里拼杀年薪百万.这些大神级的传说想必大家都有耳闻. 而渴望成为人生赢家的程序员们也怀揣着这样梦想,纷纷踏入互联网的大门.   假以时日,这些人的差距愈发明显.最直观的就是薪资水 ...

  4. Dex文件方法数超过65536怎么破?

    你的应用中的Dex 文件方法数超过了最大值65536的上限,会提示你: UNEXPECTED TOP-LEVEL EXCEPTION:java.lang.IllegalArgumentExceptio ...

  5. ACM_最短网络(最小生成树)

    Problem Description: Farmer John has been elected mayor of his town! One of his campaign promises wa ...

  6. Hadoop Hive概念学习系列之hive里的桶(十一)

    不多说,直接上干货!  Hive还可以把表或分区,组织成桶.将表或分区组织成桶有以下几个目的: 第一个目的是为看取样更高效,因为在处理大规模的数据集时,在开发.测试阶段将所有的数据全部处理一遍可能不太 ...

  7. InnoDB锁机制之Gap Lock、Next-Key Lock、Record Lock解析

    InnoDB锁机制之Gap Lock.Next-Key Lock.Record Lock解析 有意思,解释的很好

  8. maven 纯注解一步一步搭建Spring Mvc项目(入门)

    初次接触spring MVC项目,通过一段时间的学习,本文介绍一种以纯注解的方法去配置spring MVC环境,让那些配置的.xml文件统统见鬼吧. 什么是Spring MVC Spring MVC属 ...

  9. mongoDB 删除集合后,空间不释放的解决方法

    mongoDB 删除集合后,空间不释放,添加新集合,没有重新利用之前删除集合所空出来的空间,也就是数据库大小只增不减. 方法有: 1.导出导入 dump & restore 2.修复数据库 r ...

  10. (转)Arcgis for JS之Cluster聚类分析的实现

    http://blog.csdn.net/gisshixisheng/article/details/40711075 在做项目的时候,碰见了这样一个问题:给地图上标注点对象,数据是从数据库来的,包含 ...