HBase和HDFS数据互导程序

下面说说JAVA API 提供的这些类的功能和他们之间有什么样的联系。


1.HBaseConfiguration

关系:org.apache.hadoop.hbase.HBaseConfiguration

作用:通过此类可以对HBase进行配置

用法实例: Configuration config = HBaseConfiguration.create();

说明: HBaseConfiguration.create() 默认会从classpath 中查找 hbase-site.xml 中的配置信息,初始化 Configuration

2.HBaseAdmin 类

关系:org.apache.hadoop.hbase.client.HBaseAdmin

作用:提供接口关系HBase 数据库中的表信息

用法:HBaseAdmin admin = new HBaseAdmin(config);

3.Descriptor类

关系:org.apache.hadoop.hbase.HTableDescriptor

作用:HTableDescriptor 类包含了表的名字以及表的列族信息

用法:HTableDescriptor htd =new HTableDescriptor(tablename);

             构造一个表描述符指定TableName对象。

             Htd.addFamily(new HColumnDescriptor(“myFamily”));

             将列家族给定的描述符

4.HTable

关系:org.apache.hadoop.hbase.client.HTable

作用:HTable  HBase 的表通信

用法:HTable tab = new HTable(config,Bytes.toBytes(tablename));

           ResultScanner sc = tab.getScanner(Bytes.toBytes(“familyName”));

说明:获取表内列族 familyNme 的所有数据。

5.Put

关系:org.apache.hadoop.hbase.client.Put

作用:获取单个行的数据

用法:HTable table = new HTable(config,Bytes.toBytes(tablename));

           Put put = new Put(row);

           p.add(family,qualifier,value);

说明:向表 tablename 添加 “family,qualifier,value”指定的值。

6.Get

关系:org.apache.hadoop.hbase.client.Get

作用:获取单个行的数据

用法:HTable table = new HTable(config,Bytes.toBytes(tablename));

           Get get = new Get(Bytes.toBytes(row));

           Result result = table.get(get);

说明:获取 tablename 表中 row 行的对应数据

7.ResultScanner

关系:Interface

作用:获取值的接口

用法:ResultScanner scanner = table.getScanner(Bytes.toBytes(family));

           For(Result rowResult : scanner){

                   Bytes[] str = rowResult.getValue(family,column);

}

说明:循环获取行中列值。



例1 HBase之读取HDFS数据写入HBase

[java]  view plain  copy
  1. package org.hadoop.hbase;  
  2. import java.io.IOException;  
  3. import java.util.StringTokenizer;  
  4. import org.apache.hadoop.conf.Configuration;  
  5. import org.apache.hadoop.fs.Path;  
  6. import org.apache.hadoop.hbase.HBaseConfiguration;  
  7. import org.apache.hadoop.hbase.HColumnDescriptor;  
  8. import org.apache.hadoop.hbase.HTableDescriptor;  
  9. import org.apache.hadoop.hbase.client.HBaseAdmin;  
  10. import org.apache.hadoop.hbase.client.Put;  
  11. import org.apache.hadoop.hbase.io.ImmutableBytesWritable;  
  12. import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;  
  13. import org.apache.hadoop.hbase.mapreduce.TableReducer;  
  14. import org.apache.hadoop.hbase.util.Bytes;  
  15. import org.apache.hadoop.io.IntWritable;  
  16. import org.apache.hadoop.io.Text;  
  17. import org.apache.hadoop.mapreduce.Job;  
  18. import org.apache.hadoop.mapreduce.Mapper;  
  19. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  20. import org.apache.hadoop.util.GenericOptionsParser;  
  21. public class WordCountHbaseWriter {  
  22.  public static class WordCountHbaseMapper extends  
  23.    Mapper<Object, Text, Text, IntWritable> {  
  24.   private final static IntWritable one = new IntWritable(1);  
  25.   private Text word = new Text();  
  26.   public void map(Object key, Text value, Context context)  
  27.     throws IOException, InterruptedException {  
  28.    StringTokenizer itr = new StringTokenizer(value.toString());  
  29.    while (itr.hasMoreTokens()) {  
  30.     word.set(itr.nextToken());  
  31.     context.write(word, one);// 输出<key,value>为<word,one>  
  32.    }  
  33.   }  
  34.  }  
  35.  public static class WordCountHbaseReducer extends  
  36.    TableReducer<Text, IntWritable, ImmutableBytesWritable> {  
  37.   public void reduce(Text key, Iterable<IntWritable> values,  
  38.     Context context) throws IOException, InterruptedException {  
  39.    int sum = 0;  
  40.    for (IntWritable val : values) {// 遍历求和  
  41.     sum += val.get();  
  42.    }  
  43.    Put put = new Put(key.getBytes());//put实例化,每一个词存一行  
  44.    //列族为content,列修饰符为count,列值为数目  
  45.    put.add(Bytes.toBytes("content"), Bytes.toBytes("count"), Bytes.toBytes(String.valueOf(sum)));  
  46.    context.write(new ImmutableBytesWritable(key.getBytes()), put);// 输出求和后的<key,value>  
  47.   }  
  48.  }  
  49.    
  50.  public static void main(String[] args){  
  51.   String tablename = "wordcount";  
  52.   Configuration conf = HBaseConfiguration.create();  
  53.     conf.set("hbase.zookeeper.quorum""192.168.1.139");  
  54.     conf.set("hbase.zookeeper.property.clientPort""2191");  
  55.   HBaseAdmin admin = null;  
  56.   try {  
  57.    admin = new HBaseAdmin(conf);  
  58.    if(admin.tableExists(tablename)){  
  59.     System.out.println("table exists!recreating.......");  
  60.     admin.disableTable(tablename);  
  61.     admin.deleteTable(tablename);  
  62.    }  
  63.    HTableDescriptor htd = new HTableDescriptor(tablename);  
  64.    HColumnDescriptor tcd = new HColumnDescriptor("content");  
  65.    htd.addFamily(tcd);//创建列族  
  66.    admin.createTable(htd);//创建表  
  67.    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();  
  68.       if (otherArgs.length != 1) {  
  69.         System.err.println("Usage: WordCountHbaseWriter <in>");  
  70.         System.exit(2);  
  71.       }  
  72.       Job job = new Job(conf, "WordCountHbaseWriter");  
  73.   job.setNumReduceTasks(2);  
  74.       job.setJarByClass(WordCountHbaseWriter.class);  
  75.    //使用WordCountHbaseMapper类完成Map过程;  
  76.       job.setMapperClass(WordCountHbaseMapper.class);  
  77.       TableMapReduceUtil.initTableReducerJob(tablename, WordCountHbaseReducer.class, job);  
  78.       //设置任务数据的输入路径;  
  79.       FileInputFormat.addInputPath(job, new Path(otherArgs[0]));  
  80.    //设置了Map过程的输出类型,其中设置key的输出类型为Text;  
  81.       job.setOutputKeyClass(Text.class);  
  82.    //设置了Map过程的输出类型,其中设置value的输出类型为IntWritable;  
  83.       job.setOutputValueClass(IntWritable.class);  
  84.    //调用job.waitForCompletion(true) 执行任务,执行成功后退出;  
  85.       System.exit(job.waitForCompletion(true) ? 0 : 1);  
  86.   } catch (Exception e) {  
  87.    e.printStackTrace();  
  88.   } finally{  
  89.    if(admin!=null)  
  90.     try {  
  91.      admin.close();  
  92.     } catch (IOException e) {  
  93.      e.printStackTrace();  
  94.     }  
  95.   }  
  96.     
  97.  }  
  98. }  


例2 HBase之读取HBase数据写入HDFS

[java]  view plain  copy
  1. package org.hadoop.hbase;  
  2. import java.io.IOException;  
  3. import java.util.Map.Entry;  
  4. import org.apache.hadoop.conf.Configuration;  
  5. import org.apache.hadoop.fs.Path;  
  6. import org.apache.hadoop.hbase.HBaseConfiguration;  
  7. import org.apache.hadoop.hbase.client.Result;  
  8. import org.apache.hadoop.hbase.client.Scan;  
  9. import org.apache.hadoop.hbase.io.ImmutableBytesWritable;  
  10. import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;  
  11. import org.apache.hadoop.hbase.mapreduce.TableMapper;  
  12. import org.apache.hadoop.io.Text;  
  13. import org.apache.hadoop.mapreduce.Job;  
  14. import org.apache.hadoop.mapreduce.Reducer;  
  15. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  16. import org.apache.hadoop.util.GenericOptionsParser;  
  17. public class WordCountHbaseReader {  
  18.    
  19.  public static class WordCountHbaseReaderMapper extends   
  20.     TableMapper<Text,Text>{  
  21.     @Override  
  22.     protected void map(ImmutableBytesWritable key,Result value,Context context)  
  23.             throws IOException, InterruptedException {  
  24.         StringBuffer sb = new StringBuffer("");  
  25.         for(Entry<byte[],byte[]> entry:value.getFamilyMap("content".getBytes()).entrySet()){  
  26.             String str =  new String(entry.getValue());  
  27.             //将字节数组转换为String类型  
  28.             if(str != null){  
  29.                 sb.append(new String(entry.getKey()));  
  30.                 sb.append(":");  
  31.                 sb.append(str);  
  32.             }  
  33.             context.write(new Text(key.get()), new Text(new String(sb)));  
  34.         }  
  35.     }  
  36. }  
  37.  public static class WordCountHbaseReaderReduce extends Reducer<Text,Text,Text,Text>{  
  38.      private Text result = new Text();  
  39.      @Override  
  40.      protected void reduce(Text key, Iterable<Text> values,Context context)  
  41.              throws IOException, InterruptedException {  
  42.          for(Text val:values){  
  43.              result.set(val);  
  44.              context.write(key, result);  
  45.          }  
  46.      }  
  47.  }  
  48.    
  49.  public static void main(String[] args) throws Exception {  
  50.      String tablename = "wordcount";  
  51.      Configuration conf = HBaseConfiguration.create();  
  52.      conf.set("hbase.zookeeper.quorum""192.168.1.139");  
  53.      conf.set("hbase.zookeeper.property.clientPort""2191");  
  54.        
  55.      String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();  
  56.      if (otherArgs.length != 1) {  
  57.        System.err.println("Usage: WordCountHbaseReader <out>");  
  58.        System.exit(2);  
  59.      }  
  60.      Job job = new Job(conf, "WordCountHbaseReader");  
  61.      job.setJarByClass(WordCountHbaseReader.class);  
  62.      //设置任务数据的输出路径;  
  63.      FileOutputFormat.setOutputPath(job, new Path(otherArgs[0]));  
  64.      job.setReducerClass(WordCountHbaseReaderReduce.class);  
  65.      Scan scan = new Scan();  
  66.      TableMapReduceUtil.initTableMapperJob(tablename,scan,WordCountHbaseReaderMapper.class, Text.class, Text.class, job);  
  67.      //调用job.waitForCompletion(true) 执行任务,执行成功后退出;  
  68.      System.exit(job.waitForCompletion(true) ? 0 : 1);  
  69.   
  70.  }  
  71. }  


程序中用到hadoop的相关JAR包(如下图)及hbase所有jar包

wKiom1VSw0bjkI7QAABrwzSlqdo801.jpg

如果上面的API还不能满足你的要求,可以到下面这个网站里面Hbase全部API介绍

http://www.yiibai.com/hbase/

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值