hbase 自定义 endpoint coprocessor

转载地址:http://blog.csdn.net/xiao_jun_0820/article/details/27092831


hbase 自带的AggregationClient只能对单一列族的单一列进行聚合。如果想对多个列进行聚合的话,比如后面列子中说的salecount(销售量)和salemoney(销售金额),用AggregationClient只能调用两次,这样难免效率会比较低,而且两次调用一致性也不能保证(可能你sum完salecount后,再sum salemoney之前又插入了输入)。

所以只能实现一个自定义的endpoint coprocessor了。


首先自定义一个实现writable的类MyMutiSum,因为要在hadoop集群中进行传输,所以必须实现writable.用来返回每个列sum后的结果,该类实现如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.io.DataInput;  
  2. import java.io.DataOutput;  
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.hadoop.io.Writable;  
  8.   
  9. public class MyMutiSum implements Writable {  
  10.   
  11.     private List<Long> resultList = new ArrayList<Long>();  
  12.   
  13.     public MyMutiSum() {  
  14.     }  
  15.   
  16.     public MyMutiSum(int resultSize) {  
  17.         for (int i = 0; i < resultSize; i++) {  
  18.             resultList.add(0L);  
  19.         }  
  20.     }  
  21.   
  22.     public Long getSum(int i) {  
  23.         return resultList.get(i);  
  24.     }  
  25.   
  26.     public void setSum(int i, Long sum) {  
  27.         resultList.set(i, sum);  
  28.     }  
  29.   
  30.     public int getResultSize() {  
  31.         return resultList.size();  
  32.     }  
  33.   
  34.     @Override  
  35.     public void write(DataOutput out) throws IOException {  
  36.         // TODO Auto-generated method stub  
  37.         out.writeInt(resultList.size());  
  38.         for (Long v : resultList) {  
  39.             out.writeLong(v);  
  40.         }  
  41.     }  
  42.   
  43.     @Override  
  44.     public void readFields(DataInput in) throws IOException {  
  45.         // TODO Auto-generated method stub  
  46.         int size = in.readInt();  
  47.         for (int i = 0; i < size; i++) {  
  48.             resultList.add(in.readLong());  
  49.         }  
  50.     }  
  51.   
  52. }  
然后自定义一个RPC协议,里面有个方法的参数columns是将你要进行sum的多个列都传过去作为参数:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.io.IOException;  
  2.   
  3. import org.apache.hadoop.hbase.client.Scan;  
  4. import org.apache.hadoop.hbase.ipc.CoprocessorProtocol;  
  5.   
  6. public interface MyCoprocessorProtocol extends CoprocessorProtocol {  
  7.   
  8.     MyMutiSum getMutiSum(String[] columns, Scan scan) throws IOException;  
  9. }  

然后实现这个RPC协议的服务(方法):

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.io.IOException;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4.   
  5. import org.apache.commons.logging.Log;  
  6. import org.apache.commons.logging.LogFactory;  
  7. import org.apache.hadoop.hbase.KeyValue;  
  8. import org.apache.hadoop.hbase.client.Scan;  
  9. import org.apache.hadoop.hbase.coprocessor.BaseEndpointCoprocessor;  
  10. import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;  
  11. import org.apache.hadoop.hbase.regionserver.InternalScanner;  
  12. import org.apache.hadoop.hbase.util.Bytes;  
  13.   
  14. public class MyEndpointImpl extends BaseEndpointCoprocessor implements  
  15.         MyCoprocessorProtocol {  
  16.     protected static Log log = LogFactory.getLog(MyEndpointImpl.class);  
  17.   
  18.     @Override  
  19.     public MyMutiSum getMutiSum(String[] columns, Scan scan) throws IOException {  
  20.         // TODO Auto-generated method stub  
  21.         MyMutiSum result = new MyMutiSum(columns.length);  
  22.         InternalScanner scanner = ((RegionCoprocessorEnvironment) getEnvironment())  
  23.                 .getRegion().getScanner(scan);  
  24.   
  25.         List<KeyValue> keyValues = new ArrayList<KeyValue>();  
  26.         try {  
  27.             boolean hasMoreRows = false;  
  28.             do {  
  29.                 //循环每一个row的待sum的列,  
  30.                 hasMoreRows = scanner.next(keyValues);  
  31.                 for (int i = 0; i < columns.length; i++) {  
  32.                       
  33.                     String column = columns[i];  
  34.                     for (KeyValue kv : keyValues) {  
  35.                         if (column.equals(Bytes.toString(kv.getQualifier()))) {  
  36.                             byte[] value = kv.getValue();  
  37.                             if (value == null || value.length == 0) {  
  38.                             } else {  
  39.                                 Long tValue = Bytes.toLong(value);  
  40.                                 //如果是待sum的列,就将该列的值累加到之前的sum值上去。  
  41.                                 result.setSum(i, result.getSum(i) + tValue);  
  42.   
  43.                             }  
  44.                             break;  
  45.                         }  
  46.                     }  
  47.                 }  
  48.   
  49.                 keyValues.clear();  
  50.             } while (hasMoreRows);  
  51.         } finally {  
  52.             scanner.close();  
  53.         }  
  54.         log.debug("Sum from this region is "  
  55.                 + ((RegionCoprocessorEnvironment) getEnvironment()).getRegion()  
  56.                         .getRegionNameAsString() + ": ");  
  57.   
  58.         for (int i = 0; i < columns.length; i++) {  
  59.             log.debug(columns[i] + " " + result.getSum(i));  
  60.         }  
  61.         //将sum后的自定义writable对象返回  
  62.         return result;  
  63.     }  
  64.   
  65. }  

接下来我们可以实现一个rpc client:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.io.IOException;  
  2.   
  3. import org.apache.commons.logging.Log;  
  4. import org.apache.commons.logging.LogFactory;  
  5. import org.apache.hadoop.conf.Configuration;  
  6. import org.apache.hadoop.hbase.HBaseConfiguration;  
  7. import org.apache.hadoop.hbase.client.HTable;  
  8. import org.apache.hadoop.hbase.client.Scan;  
  9. import org.apache.hadoop.hbase.client.coprocessor.Batch;  
  10. import org.apache.hadoop.hbase.util.Bytes;  
  11.   
  12. public class MyEndpointClient {  
  13.     protected static Log log = LogFactory.getLog(MyEndpointClient.class);  
  14.   
  15.     private Configuration conf;  
  16.   
  17.     public MyEndpointClient(Configuration conf) {  
  18.         this.conf = conf;  
  19.     }  
  20.   
  21.     public MyMutiSum mutiSum(String tableName, String cf,  
  22.             final String[] columns, final Scan scan) throws Throwable {  
  23.         class MutiSumCallBack implements Batch.Callback<MyMutiSum> {  
  24.   
  25.             MyMutiSum sumVal = null;  
  26.   
  27.             public MyMutiSum getSumResult() {  
  28.                 return sumVal;  
  29.             }  
  30.   
  31.             @Override  
  32.             public void update(byte[] region, byte[] row, MyMutiSum result) {  
  33.                 // TODO Auto-generated method stub  
  34.                 sumVal = add(sumVal, result);  
  35.             }  
  36.   
  37.             public MyMutiSum add(MyMutiSum l1, MyMutiSum l2) {  
  38.                 if (l1 == null ^ l2 == null) {  
  39.                     return (l1 == null) ? l2 : l1; // either of one is null.  
  40.                 } else if (l1 == null// both are null  
  41.                     return null;  
  42.   
  43.                 MyMutiSum mutiSum = new MyMutiSum(columns.length);  
  44.   
  45.                 for (int i = 0; i < columns.length; i++) {  
  46.                     mutiSum.setSum(i, l1.getSum(i) + l2.getSum(i));  
  47.                 }  
  48.   
  49.                 return mutiSum;  
  50.             }  
  51.   
  52.         }  
  53.   
  54.         MutiSumCallBack sumCallBack = new MutiSumCallBack();  
  55.   
  56.         HTable table = null;  
  57.   
  58.         for (int i = 0; i < columns.length; i++) {  
  59.             scan.addColumn(Bytes.toBytes(cf), Bytes.toBytes(columns[i]));  
  60.         }  
  61.   
  62.         try {  
  63.             table = new HTable(conf, tableName);  
  64.             // 根据startRow和stopRow确定regionserver,即RPC  
  65.             // SERVER,在startRow~stopRow范围的region上执行rpc调用  
  66.             // 所以这个方法其实发起了多个RPC调用,每个RPC调用返回后都会调用sumCallBack的update方法,将自己执行的结果通过update方法累加到sumCallBack的sumVal上  
  67.             table.coprocessorExec(MyCoprocessorProtocol.class,  
  68.                     scan.getStartRow(), scan.getStopRow(),  
  69.                     new Batch.Call<MyCoprocessorProtocol, MyMutiSum>() {  
  70.   
  71.                         @Override  
  72.                         public MyMutiSum call(MyCoprocessorProtocol instance)  
  73.                                 throws IOException {  
  74.                             // TODO Auto-generated method stub  
  75.                             // instance.getMutiSum会转化成对region上的指定的MyCoprocessorProtocol的实现类的该方法的rpc调用  
  76.                             return instance.getMutiSum(columns, scan);  
  77.                         }  
  78.   
  79.                     }, sumCallBack);  
  80.         } finally {  
  81.             if (table != null) {  
  82.                 table.close();  
  83.             }  
  84.         }  
  85.         // 返回的是sumCallBack的sumVal,即所有region结果通过update的累加。  
  86.         return sumCallBack.getSumResult();  
  87.     }  
  88.   
  89.   
  90. }  

ok,现在我们将这三个类打包成MutiSum.jar,上传到hdfs上去,我这里传的目录为hdfs://master24:9000/user/hadoop/jars/MutiSum.jar。

接下来我们将这个自定义的cp设置到member4这个表上去,通过API来实现:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import org.apache.hadoop.conf.Configuration;  
  2. import org.apache.hadoop.fs.Path;  
  3. import org.apache.hadoop.hbase.HBaseConfiguration;  
  4. import org.apache.hadoop.hbase.HTableDescriptor;  
  5. import org.apache.hadoop.hbase.MasterNotRunningException;  
  6. import org.apache.hadoop.hbase.client.HBaseAdmin;  
  7. import org.apache.hadoop.hbase.util.Bytes;  
  8.   
  9. public class SetCoprocessor {  
  10.   
  11.     /** 
  12.      * @param args 
  13.      * @throws Exception 
  14.      * @throws MasterNotRunningException 
  15.      */  
  16.     public static void main(String[] args) throws MasterNotRunningException,  
  17.             Exception {  
  18.         // TODO Auto-generated method stub  
  19.         byte[] tableName = Bytes.toBytes("member4");  
  20.         Configuration conf = HBaseConfiguration.create();  
  21.         HBaseAdmin admin = new HBaseAdmin(conf);  
  22.         admin.disableTable(tableName);  
  23.   
  24.         HTableDescriptor htd = admin.getTableDescriptor(tableName);  
  25.         htd.addCoprocessor("com.besttone.coprocessor.MyEndpointImpl"new Path(  
  26.                 "hdfs://master24:9000/user/hadoop/jars/MutiSum.jar"), 1001,  
  27.                 null);  
  28.         admin.modifyTable(tableName, htd);  
  29.         admin.enableTable(tableName);  
  30.         admin.close();  
  31.     }  
  32.   
  33. }  

所有都准备就绪了,接下来就可以写一个main函数来测试调用一下这个cp了:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * @param args 
  3.  * @throws Throwable 
  4.  */  
  5. public static void main(String[] args) throws Throwable {  
  6.     // TODO Auto-generated method stub  
  7.     // 我们建了一个测试表member4,里面info列族上有两个列,一个salecount销售量,一个salemoney销售额,我们通过上面自定义的cp,返回总销售量和总销售额  
  8.     final String[] columns = new String[] { "salecount""salemoney" };  
  9.     Configuration conf = HBaseConfiguration.create();  
  10.   
  11.     final Scan scan;  
  12.     scan = new Scan();  
  13.   
  14.     scan.addColumn(Bytes.toBytes("info"), Bytes.toBytes("salecount"));  
  15.     scan.addColumn(Bytes.toBytes("info"), Bytes.toBytes("salemoney"));  
  16.   
  17.     MyEndpointClient client = new MyEndpointClient(conf);  
  18.   
  19.     MyMutiSum mutiSum = client.mutiSum("member4""info", columns, scan);  
  20.   
  21.     for (int i = 0; i < columns.length; i++) {  
  22.         System.out.println(columns[i] + " sum is :" + mutiSum.getSum(i));  
  23.     }  
  24.   
  25. }  

针对以下代码补充说明一下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. table.coprocessorExec(MyCoprocessorProtocol.class,  
  2.                     scan.getStartRow(), scan.getStopRow(),  
  3.                     new Batch.Call<MyCoprocessorProtocol, MyMutiSum>() {  
  4.   
  5.                         @Override  
  6.                         public MyMutiSum call(MyCoprocessorProtocol instance)  
  7.                                 throws IOException {  
  8.                             // TODO Auto-generated method stub  
  9.                             // instance.getMutiSum会转化成对region上的指定的MyCoprocessorProtocol的实现类的该方法的rpc调用  
  10.                             return instance.getMutiSum(columns, scan);  
  11.                         }  
  12.   
  13.                     }, sumCallBack);  

hbase 权威指南上的例子是在call方法内部调用多个instance的方法,然后return 一个Pair,这种也是可行的,不过还是尽量封装成调用instance 的一个方法发起一个RPC,调用多个方法其实发起的RPC调用更多。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值