hbase协处理器编码实例

news2024/12/24 8:24:41

Observer协处理器通常在一个特定的事件(诸如GetPut)之前或之后发生,相当于RDBMS中的触发器。Endpoint协处理器则类似于RDBMS中的存储过程,因为它可以让你在RegionServer上对数据执行自定义计算,而不是在客户端上执行计算。

本文是以上两者的简单实例,使用的环境:环境 jdk1.8 hadoop2.6.5 hbase1.2.4。

1、Endpoint实例 
1> 编写适用于protobuf的proto文件,如下,尽量不要带注释,因为编译时可能出现乱码        

option java_package = "com.endpoint.test";
option java_outer_classname = "Sum";
option java_generic_services = true;
option java_generate_equals_and_hash = true;
option optimize_for = SPEED;
 
message SumRequest {
    required string family = 1;
    required string column = 2;
}
message SumResponse {
    required int64 sum = 1 [default = 0];
}
service SumService {
    rpc getSum(SumRequest)
        returns (SumResponse);
}

2> 编译上面的proto文件
使用protoc程序进行编译,linux下或者windows均可,protoc程序可以直接从github下载:Releases · protocolbuffers/protobuf · GitHub,也可以自己编译生成,参见protobuf的编译安装

注意,编译的版本要与hadoop以及hbase使用的版本相同,或者略高,但最好不要过高,hadoop2.6.5 hbase1.2.4使用的都是protobuf2.5.0的版本,写此篇文章时的最新版为3.1.0

(高版本必须指定syntax,例如proto3的syntax在第一行非空白非注释行,必须写:syntax = "proto3",字段规则移除了 “required”,并把 “optional” 改名为 “singular”,移除了 default 选项。可搜索Protobuf 的 proto3 与 proto2 的区别进行了解。)下载的话选择带win或linux的版本,这是编译好的版本。有很多带具体语言的版本,是一些具体某种语言的发行版源码包。为了与hbase以及hadoop统一起来,此处用的是protoc-2.5.0-win32.zip。

解压文件:

使用windows命令行进入上面的目录,执行以下命令即可:

protoc.exe sum1.proto --java_out=./

         高版本有编译好的适用于linux下的protoc程序文件,低版本没有。在linux下执行以下命令:

protoc sum.proto --java_out=./

结果都一样,生成的代码参见折叠部分,有很多,因为上面文件中指定java_outer_classname = "Sum",所以会生成Sum类,将这个类引入到项目中,注意项目的包名称与上面文件中指定(option java_package = "com.endpoint.test")的名称要一致。

// Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: sumcode.proto
 
 package com.endpoint.test;
 
 public final class Sum {
   private Sum() {}
   public static void registerAllExtensions(
       com.google.protobuf.ExtensionRegistry registry) {
   }
   public interface SumRequestOrBuilder
       extends com.google.protobuf.MessageOrBuilder {
 
     // required string family = 1;
     /**
      * <code>required string family = 1;</code>
      */
     boolean hasFamily();
     /**
      * <code>required string family = 1;</code>
      */
     java.lang.String getFamily();
     /**
      * <code>required string family = 1;</code>
      */
     com.google.protobuf.ByteString
         getFamilyBytes();
 
     // required string column = 2;
     /**
      * <code>required string column = 2;</code>
      */
     boolean hasColumn();
     /**
      * <code>required string column = 2;</code>
      */
     java.lang.String getColumn();
     /**
      * <code>required string column = 2;</code>
      */
     com.google.protobuf.ByteString
         getColumnBytes();
   }
   /**
    * Protobuf type {@code SumRequest}
    */
   public static final class SumRequest extends
       com.google.protobuf.GeneratedMessage
       implements SumRequestOrBuilder {
     // Use SumRequest.newBuilder() to construct.
     private SumRequest(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
       super(builder);
       this.unknownFields = builder.getUnknownFields();
     }
     private SumRequest(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
 
     private static final SumRequest defaultInstance;
     public static SumRequest getDefaultInstance() {
       return defaultInstance;
     }
 
     public SumRequest getDefaultInstanceForType() {
       return defaultInstance;
     }
 
     private final com.google.protobuf.UnknownFieldSet unknownFields;
     @java.lang.Override
     public final com.google.protobuf.UnknownFieldSet
         getUnknownFields() {
       return this.unknownFields;
     }
     private SumRequest(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       initFields();
       int mutable_bitField0_ = 0;
       com.google.protobuf.UnknownFieldSet.Builder unknownFields =
           com.google.protobuf.UnknownFieldSet.newBuilder();
       try {
         boolean done = false;
         while (!done) {
           int tag = input.readTag();
           switch (tag) {
             case 0:
               done = true;
               break;
             default: {
               if (!parseUnknownField(input, unknownFields,
                                      extensionRegistry, tag)) {
                 done = true;
               }
               break;
             }
             case 10: {
               bitField0_ |= 0x00000001;
               family_ = input.readBytes();
               break;
             }
             case 18: {
               bitField0_ |= 0x00000002;
               column_ = input.readBytes();
               break;
             }
           }
         }
       } catch (com.google.protobuf.InvalidProtocolBufferException e) {
         throw e.setUnfinishedMessage(this);
       } catch (java.io.IOException e) {
         throw new com.google.protobuf.InvalidProtocolBufferException(
             e.getMessage()).setUnfinishedMessage(this);
       } finally {
         this.unknownFields = unknownFields.build();
         makeExtensionsImmutable();
       }
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
       return com.endpoint.test.Sum.internal_static_SumRequest_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
       return com.endpoint.test.Sum.internal_static_SumRequest_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
               com.endpoint.test.Sum.SumRequest.class, com.endpoint.test.Sum.SumRequest.Builder.class);
     }
 
     public static com.google.protobuf.Parser<SumRequest> PARSER =
         new com.google.protobuf.AbstractParser<SumRequest>() {
       public SumRequest parsePartialFrom(
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws com.google.protobuf.InvalidProtocolBufferException {
         return new SumRequest(input, extensionRegistry);
       }
     };
 
     @java.lang.Override
     public com.google.protobuf.Parser<SumRequest> getParserForType() {
       return PARSER;
     }
 
     private int bitField0_;
     // required string family = 1;
     public static final int FAMILY_FIELD_NUMBER = 1;
     private java.lang.Object family_;
     /**
      * <code>required string family = 1;</code>
      */
     public boolean hasFamily() {
       return ((bitField0_ & 0x00000001) == 0x00000001);
     }
     /**
      * <code>required string family = 1;</code>
      */
     public java.lang.String getFamily() {
       java.lang.Object ref = family_;
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
         com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
           family_ = s;
         }
         return s;
       }
     }
     /**
      * <code>required string family = 1;</code>
      */
     public com.google.protobuf.ByteString
         getFamilyBytes() {
       java.lang.Object ref = family_;
       if (ref instanceof java.lang.String) {
         com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         family_ = b;
         return b;
       } else {
         return (com.google.protobuf.ByteString) ref;
       }
     }
 
     // required string column = 2;
     public static final int COLUMN_FIELD_NUMBER = 2;
     private java.lang.Object column_;
     /**
      * <code>required string column = 2;</code>
      */
     public boolean hasColumn() {
       return ((bitField0_ & 0x00000002) == 0x00000002);
     }
     /**
      * <code>required string column = 2;</code>
      */
     public java.lang.String getColumn() {
       java.lang.Object ref = column_;
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
         com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
           column_ = s;
         }
         return s;
       }
     }
     /**
      * <code>required string column = 2;</code>
      */
     public com.google.protobuf.ByteString
         getColumnBytes() {
       java.lang.Object ref = column_;
       if (ref instanceof java.lang.String) {
         com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         column_ = b;
         return b;
       } else {
         return (com.google.protobuf.ByteString) ref;
       }
     }
 
     private void initFields() {
       family_ = "";
       column_ = "";
     }
     private byte memoizedIsInitialized = -1;
     public final boolean isInitialized() {
       byte isInitialized = memoizedIsInitialized;
       if (isInitialized != -1) return isInitialized == 1;
 
       if (!hasFamily()) {
         memoizedIsInitialized = 0;
         return false;
       }
       if (!hasColumn()) {
         memoizedIsInitialized = 0;
         return false;
       }
       memoizedIsInitialized = 1;
       return true;
     }
 
     public void writeTo(com.google.protobuf.CodedOutputStream output)
                         throws java.io.IOException {
       getSerializedSize();
       if (((bitField0_ & 0x00000001) == 0x00000001)) {
         output.writeBytes(1, getFamilyBytes());
       }
       if (((bitField0_ & 0x00000002) == 0x00000002)) {
         output.writeBytes(2, getColumnBytes());
       }
       getUnknownFields().writeTo(output);
     }
 
     private int memoizedSerializedSize = -1;
     public int getSerializedSize() {
       int size = memoizedSerializedSize;
       if (size != -1) return size;
 
       size = 0;
       if (((bitField0_ & 0x00000001) == 0x00000001)) {
         size += com.google.protobuf.CodedOutputStream
           .computeBytesSize(1, getFamilyBytes());
       }
       if (((bitField0_ & 0x00000002) == 0x00000002)) {
         size += com.google.protobuf.CodedOutputStream
           .computeBytesSize(2, getColumnBytes());
       }
       size += getUnknownFields().getSerializedSize();
       memoizedSerializedSize = size;
       return size;
     }
 
     private static final long serialVersionUID = 0L;
     @java.lang.Override
     protected java.lang.Object writeReplace()
         throws java.io.ObjectStreamException {
       return super.writeReplace();
     }
 
     @java.lang.Override
     public boolean equals(final java.lang.Object obj) {
       if (obj == this) {
        return true;
       }
       if (!(obj instanceof com.endpoint.test.Sum.SumRequest)) {
         return super.equals(obj);
       }
       com.endpoint.test.Sum.SumRequest other = (com.endpoint.test.Sum.SumRequest) obj;
 
       boolean result = true;
       result = result && (hasFamily() == other.hasFamily());
       if (hasFamily()) {
         result = result && getFamily()
             .equals(other.getFamily());
       }
       result = result && (hasColumn() == other.hasColumn());
       if (hasColumn()) {
         result = result && getColumn()
             .equals(other.getColumn());
       }
       result = result &&
           getUnknownFields().equals(other.getUnknownFields());
       return result;
     }
 
     private int memoizedHashCode = 0;
     @java.lang.Override
     public int hashCode() {
       if (memoizedHashCode != 0) {
         return memoizedHashCode;
       }
       int hash = 41;
       hash = (19 * hash) + getDescriptorForType().hashCode();
       if (hasFamily()) {
         hash = (37 * hash) + FAMILY_FIELD_NUMBER;
         hash = (53 * hash) + getFamily().hashCode();
       }
       if (hasColumn()) {
         hash = (37 * hash) + COLUMN_FIELD_NUMBER;
         hash = (53 * hash) + getColumn().hashCode();
       }
       hash = (29 * hash) + getUnknownFields().hashCode();
       memoizedHashCode = hash;
       return hash;
     }
 
     public static com.endpoint.test.Sum.SumRequest parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
     public static com.endpoint.test.Sum.SumRequest parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumRequest parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
     public static com.endpoint.test.Sum.SumRequest parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumRequest parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
     public static com.endpoint.test.Sum.SumRequest parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumRequest parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
     public static com.endpoint.test.Sum.SumRequest parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumRequest parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
     public static com.endpoint.test.Sum.SumRequest parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
     public static Builder newBuilder(com.endpoint.test.Sum.SumRequest prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
 
     @java.lang.Override
     protected Builder newBuilderForType(
         com.google.protobuf.GeneratedMessage.BuilderParent parent) {
       Builder builder = new Builder(parent);
       return builder;
     }
     /**
      * Protobuf type {@code SumRequest}
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
        implements com.endpoint.test.Sum.SumRequestOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
         return com.endpoint.test.Sum.internal_static_SumRequest_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
         return com.endpoint.test.Sum.internal_static_SumRequest_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
                 com.endpoint.test.Sum.SumRequest.class, com.endpoint.test.Sum.SumRequest.Builder.class);
       }
 
       // Construct using com.endpoint.test.Sum.SumRequest.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
 
       private Builder(
           com.google.protobuf.GeneratedMessage.BuilderParent parent) {
         super(parent);
         maybeForceBuilderInitialization();
       }
       private void maybeForceBuilderInitialization() {
         if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
         }
       }
       private static Builder create() {
         return new Builder();
       }
 
       public Builder clear() {
         super.clear();
         family_ = "";
         bitField0_ = (bitField0_ & ~0x00000001);
         column_ = "";
         bitField0_ = (bitField0_ & ~0x00000002);
         return this;
       }
 
       public Builder clone() {
         return create().mergeFrom(buildPartial());
       }
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
         return com.endpoint.test.Sum.internal_static_SumRequest_descriptor;
       }
 
       public com.endpoint.test.Sum.SumRequest getDefaultInstanceForType() {
         return com.endpoint.test.Sum.SumRequest.getDefaultInstance();
       }
 
       public com.endpoint.test.Sum.SumRequest build() {
         com.endpoint.test.Sum.SumRequest result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
       public com.endpoint.test.Sum.SumRequest buildPartial() {
         com.endpoint.test.Sum.SumRequest result = new com.endpoint.test.Sum.SumRequest(this);
         int from_bitField0_ = bitField0_;
         int to_bitField0_ = 0;
         if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
           to_bitField0_ |= 0x00000001;
         }
         result.family_ = family_;
         if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
           to_bitField0_ |= 0x00000002;
         }
         result.column_ = column_;
         result.bitField0_ = to_bitField0_;
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
         if (other instanceof com.endpoint.test.Sum.SumRequest) {
           return mergeFrom((com.endpoint.test.Sum.SumRequest)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
       public Builder mergeFrom(com.endpoint.test.Sum.SumRequest other) {
         if (other == com.endpoint.test.Sum.SumRequest.getDefaultInstance()) return this;
         if (other.hasFamily()) {
           bitField0_ |= 0x00000001;
           family_ = other.family_;
           onChanged();
         }
         if (other.hasColumn()) {
           bitField0_ |= 0x00000002;
           column_ = other.column_;
           onChanged();
         }
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
 
       public final boolean isInitialized() {
         if (!hasFamily()) {
 
           return false;
         }
         if (!hasColumn()) {
 
           return false;
         }
         return true;
       }
 
       public Builder mergeFrom(
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
         com.endpoint.test.Sum.SumRequest parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
           parsedMessage = (com.endpoint.test.Sum.SumRequest) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
             mergeFrom(parsedMessage);
           }
         }
         return this;
       }
       private int bitField0_;
 
       // required string family = 1;
       private java.lang.Object family_ = "";
       /**
        * <code>required string family = 1;</code>
        */
       public boolean hasFamily() {
         return ((bitField0_ & 0x00000001) == 0x00000001);
       }
       /**
        * <code>required string family = 1;</code>
        */
       public java.lang.String getFamily() {
         java.lang.Object ref = family_;
         if (!(ref instanceof java.lang.String)) {
           java.lang.String s = ((com.google.protobuf.ByteString) ref)
               .toStringUtf8();
           family_ = s;
           return s;
         } else {
           return (java.lang.String) ref;
         }
       }
       /**
        * <code>required string family = 1;</code>
        */
       public com.google.protobuf.ByteString
           getFamilyBytes() {
         java.lang.Object ref = family_;
         if (ref instanceof String) {
           com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           family_ = b;
           return b;
         } else {
           return (com.google.protobuf.ByteString) ref;
         }
       }
       /**
        * <code>required string family = 1;</code>
        */
       public Builder setFamily(
           java.lang.String value) {
         if (value == null) {
     throw new NullPointerException();
   }
   bitField0_ |= 0x00000001;
         family_ = value;
         onChanged();
         return this;
       }
       /**
        * <code>required string family = 1;</code>
        */
       public Builder clearFamily() {
         bitField0_ = (bitField0_ & ~0x00000001);
         family_ = getDefaultInstance().getFamily();
         onChanged();
         return this;
       }
       /**
        * <code>required string family = 1;</code>
        */
       public Builder setFamilyBytes(
           com.google.protobuf.ByteString value) {
         if (value == null) {
     throw new NullPointerException();
   }
   bitField0_ |= 0x00000001;
         family_ = value;
         onChanged();
         return this;
       }
 
       // required string column = 2;
       private java.lang.Object column_ = "";
       /**
        * <code>required string column = 2;</code>
        */
       public boolean hasColumn() {
         return ((bitField0_ & 0x00000002) == 0x00000002);
       }
       /**
        * <code>required string column = 2;</code>
        */
       public java.lang.String getColumn() {
         java.lang.Object ref = column_;
         if (!(ref instanceof java.lang.String)) {
           java.lang.String s = ((com.google.protobuf.ByteString) ref)
               .toStringUtf8();
           column_ = s;
           return s;
         } else {
           return (java.lang.String) ref;
         }
       }
       /**
        * <code>required string column = 2;</code>
        */
       public com.google.protobuf.ByteString
           getColumnBytes() {
         java.lang.Object ref = column_;
         if (ref instanceof String) {
           com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           column_ = b;
           return b;
         } else {
           return (com.google.protobuf.ByteString) ref;
         }
       }
       /**
        * <code>required string column = 2;</code>
        */
       public Builder setColumn(
           java.lang.String value) {
         if (value == null) {
     throw new NullPointerException();
   }
   bitField0_ |= 0x00000002;
         column_ = value;
         onChanged();
         return this;
       }
       /**
        * <code>required string column = 2;</code>
        */
       public Builder clearColumn() {
         bitField0_ = (bitField0_ & ~0x00000002);
         column_ = getDefaultInstance().getColumn();
         onChanged();
         return this;
       }
       /**
        * <code>required string column = 2;</code>
        */
       public Builder setColumnBytes(
           com.google.protobuf.ByteString value) {
         if (value == null) {
     throw new NullPointerException();
   }
   bitField0_ |= 0x00000002;
         column_ = value;
         onChanged();
         return this;
       }
 
       // @@protoc_insertion_point(builder_scope:SumRequest)
     }
 
     static {
       defaultInstance = new SumRequest(true);
       defaultInstance.initFields();
     }
 
     // @@protoc_insertion_point(class_scope:SumRequest)
   }
 
   public interface SumResponseOrBuilder
       extends com.google.protobuf.MessageOrBuilder {
 
     // required int64 sum = 1 [default = 0];
     /**
      * <code>required int64 sum = 1 [default = 0];</code>
      */
     boolean hasSum();
     /**
      * <code>required int64 sum = 1 [default = 0];</code>
      */
     long getSum();
   }
   /**
    * Protobuf type {@code SumResponse}
    */
   public static final class SumResponse extends
       com.google.protobuf.GeneratedMessage
       implements SumResponseOrBuilder {
     // Use SumResponse.newBuilder() to construct.
     private SumResponse(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
       super(builder);
       this.unknownFields = builder.getUnknownFields();
     }
     private SumResponse(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
 
     private static final SumResponse defaultInstance;
     public static SumResponse getDefaultInstance() {
       return defaultInstance;
     }
 
     public SumResponse getDefaultInstanceForType() {
       return defaultInstance;
     }
 
     private final com.google.protobuf.UnknownFieldSet unknownFields;
     @java.lang.Override
     public final com.google.protobuf.UnknownFieldSet
         getUnknownFields() {
       return this.unknownFields;
     }
     private SumResponse(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       initFields();
       int mutable_bitField0_ = 0;
       com.google.protobuf.UnknownFieldSet.Builder unknownFields =
           com.google.protobuf.UnknownFieldSet.newBuilder();
       try {
         boolean done = false;
         while (!done) {
           int tag = input.readTag();
           switch (tag) {
             case 0:
               done = true;
               break;
             default: {
               if (!parseUnknownField(input, unknownFields,
                                      extensionRegistry, tag)) {
                 done = true;
               }
               break;
             }
             case 8: {
               bitField0_ |= 0x00000001;
               sum_ = input.readInt64();
               break;
             }
           }
         }
       } catch (com.google.protobuf.InvalidProtocolBufferException e) {
         throw e.setUnfinishedMessage(this);
       } catch (java.io.IOException e) {
         throw new com.google.protobuf.InvalidProtocolBufferException(
             e.getMessage()).setUnfinishedMessage(this);
       } finally {
         this.unknownFields = unknownFields.build();
         makeExtensionsImmutable();
       }
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
       return com.endpoint.test.Sum.internal_static_SumResponse_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
       return com.endpoint.test.Sum.internal_static_SumResponse_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
               com.endpoint.test.Sum.SumResponse.class, com.endpoint.test.Sum.SumResponse.Builder.class);
     }
 
     public static com.google.protobuf.Parser<SumResponse> PARSER =
         new com.google.protobuf.AbstractParser<SumResponse>() {
       public SumResponse parsePartialFrom(
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws com.google.protobuf.InvalidProtocolBufferException {
         return new SumResponse(input, extensionRegistry);
       }
     };
 
     @java.lang.Override
     public com.google.protobuf.Parser<SumResponse> getParserForType() {
       return PARSER;
     }
 
     private int bitField0_;
     // required int64 sum = 1 [default = 0];
     public static final int SUM_FIELD_NUMBER = 1;
     private long sum_;
     /**
      * <code>required int64 sum = 1 [default = 0];</code>
      */
     public boolean hasSum() {
       return ((bitField0_ & 0x00000001) == 0x00000001);
     }
     /**
      * <code>required int64 sum = 1 [default = 0];</code>
      */
     public long getSum() {
       return sum_;
     }
 
     private void initFields() {
       sum_ = 0L;
     }
     private byte memoizedIsInitialized = -1;
     public final boolean isInitialized() {
       byte isInitialized = memoizedIsInitialized;
       if (isInitialized != -1) return isInitialized == 1;
 
       if (!hasSum()) {
         memoizedIsInitialized = 0;
         return false;
       }
       memoizedIsInitialized = 1;
       return true;
     }
 
     public void writeTo(com.google.protobuf.CodedOutputStream output)
                         throws java.io.IOException {
       getSerializedSize();
       if (((bitField0_ & 0x00000001) == 0x00000001)) {
         output.writeInt64(1, sum_);
       }
       getUnknownFields().writeTo(output);
     }
 
     private int memoizedSerializedSize = -1;
     public int getSerializedSize() {
       int size = memoizedSerializedSize;
       if (size != -1) return size;
 
       size = 0;
       if (((bitField0_ & 0x00000001) == 0x00000001)) {
         size += com.google.protobuf.CodedOutputStream
           .computeInt64Size(1, sum_);
       }
       size += getUnknownFields().getSerializedSize();
       memoizedSerializedSize = size;
       return size;
     }
 
     private static final long serialVersionUID = 0L;
     @java.lang.Override
     protected java.lang.Object writeReplace()
         throws java.io.ObjectStreamException {
       return super.writeReplace();
     }
 
     @java.lang.Override
     public boolean equals(final java.lang.Object obj) {
       if (obj == this) {
        return true;
       }
       if (!(obj instanceof com.endpoint.test.Sum.SumResponse)) {
         return super.equals(obj);
       }
       com.endpoint.test.Sum.SumResponse other = (com.endpoint.test.Sum.SumResponse) obj;
 
       boolean result = true;
       result = result && (hasSum() == other.hasSum());
       if (hasSum()) {
         result = result && (getSum()
             == other.getSum());
       }
       result = result &&
           getUnknownFields().equals(other.getUnknownFields());
       return result;
     }
 
     private int memoizedHashCode = 0;
     @java.lang.Override
     public int hashCode() {
       if (memoizedHashCode != 0) {
         return memoizedHashCode;
       }
       int hash = 41;
       hash = (19 * hash) + getDescriptorForType().hashCode();
       if (hasSum()) {
         hash = (37 * hash) + SUM_FIELD_NUMBER;
         hash = (53 * hash) + hashLong(getSum());
       }
       hash = (29 * hash) + getUnknownFields().hashCode();
       memoizedHashCode = hash;
       return hash;
     }
 
     public static com.endpoint.test.Sum.SumResponse parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
     public static com.endpoint.test.Sum.SumResponse parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumResponse parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
     public static com.endpoint.test.Sum.SumResponse parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumResponse parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
     public static com.endpoint.test.Sum.SumResponse parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumResponse parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
     public static com.endpoint.test.Sum.SumResponse parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
     public static com.endpoint.test.Sum.SumResponse parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
     public static com.endpoint.test.Sum.SumResponse parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
     public static Builder newBuilder(com.endpoint.test.Sum.SumResponse prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
 
     @java.lang.Override
     protected Builder newBuilderForType(
         com.google.protobuf.GeneratedMessage.BuilderParent parent) {
       Builder builder = new Builder(parent);
       return builder;
     }
     /**
      * Protobuf type {@code SumResponse}
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
        implements com.endpoint.test.Sum.SumResponseOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
         return com.endpoint.test.Sum.internal_static_SumResponse_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
         return com.endpoint.test.Sum.internal_static_SumResponse_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
                 com.endpoint.test.Sum.SumResponse.class, com.endpoint.test.Sum.SumResponse.Builder.class);
       }
 
       // Construct using com.endpoint.test.Sum.SumResponse.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
 
       private Builder(
           com.google.protobuf.GeneratedMessage.BuilderParent parent) {
         super(parent);
         maybeForceBuilderInitialization();
       }
       private void maybeForceBuilderInitialization() {
         if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
         }
       }
       private static Builder create() {
         return new Builder();
       }
 
       public Builder clear() {
         super.clear();
         sum_ = 0L;
         bitField0_ = (bitField0_ & ~0x00000001);
         return this;
       }
 
       public Builder clone() {
         return create().mergeFrom(buildPartial());
       }
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
         return com.endpoint.test.Sum.internal_static_SumResponse_descriptor;
       }
 
       public com.endpoint.test.Sum.SumResponse getDefaultInstanceForType() {
         return com.endpoint.test.Sum.SumResponse.getDefaultInstance();
       }
 
       public com.endpoint.test.Sum.SumResponse build() {
         com.endpoint.test.Sum.SumResponse result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
       public com.endpoint.test.Sum.SumResponse buildPartial() {
         com.endpoint.test.Sum.SumResponse result = new com.endpoint.test.Sum.SumResponse(this);
         int from_bitField0_ = bitField0_;
         int to_bitField0_ = 0;
         if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
           to_bitField0_ |= 0x00000001;
         }
         result.sum_ = sum_;
         result.bitField0_ = to_bitField0_;
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
         if (other instanceof com.endpoint.test.Sum.SumResponse) {
           return mergeFrom((com.endpoint.test.Sum.SumResponse)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
       public Builder mergeFrom(com.endpoint.test.Sum.SumResponse other) {
         if (other == com.endpoint.test.Sum.SumResponse.getDefaultInstance()) return this;
         if (other.hasSum()) {
           setSum(other.getSum());
         }
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
 
       public final boolean isInitialized() {
         if (!hasSum()) {
 
           return false;
         }
         return true;
       }
 
       public Builder mergeFrom(
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
         com.endpoint.test.Sum.SumResponse parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
           parsedMessage = (com.endpoint.test.Sum.SumResponse) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
             mergeFrom(parsedMessage);
           }
         }
         return this;
       }
       private int bitField0_;
 
       // required int64 sum = 1 [default = 0];
       private long sum_ ;
       /**
        * <code>required int64 sum = 1 [default = 0];</code>
        */
       public boolean hasSum() {
         return ((bitField0_ & 0x00000001) == 0x00000001);
       }
       /**
        * <code>required int64 sum = 1 [default = 0];</code>
        */
       public long getSum() {
         return sum_;
       }
       /**
        * <code>required int64 sum = 1 [default = 0];</code>
        */
       public Builder setSum(long value) {
         bitField0_ |= 0x00000001;
         sum_ = value;
         onChanged();
         return this;
       }
       /**
        * <code>required int64 sum = 1 [default = 0];</code>
        */
       public Builder clearSum() {
         bitField0_ = (bitField0_ & ~0x00000001);
         sum_ = 0L;
         onChanged();
         return this;
       }
 
       // @@protoc_insertion_point(builder_scope:SumResponse)
     }
 
     static {
       defaultInstance = new SumResponse(true);
       defaultInstance.initFields();
     }
 
     // @@protoc_insertion_point(class_scope:SumResponse)
   }
 
   /**
    * Protobuf service {@code SumService}
    */
   public static abstract class SumService
       implements com.google.protobuf.Service {
     protected SumService() {}
 
     public interface Interface {
       /**
        * <code>rpc getSum(.SumRequest) returns (.SumResponse);</code>
        */
       public abstract void getSum(
           com.google.protobuf.RpcController controller,
           com.endpoint.test.Sum.SumRequest request,
           com.google.protobuf.RpcCallback<com.endpoint.test.Sum.SumResponse> done);
 
     }
 
     public static com.google.protobuf.Service newReflectiveService(
         final Interface impl) {
       return new SumService() {
         @java.lang.Override
         public  void getSum(
             com.google.protobuf.RpcController controller,
             com.endpoint.test.Sum.SumRequest request,
             com.google.protobuf.RpcCallback<com.endpoint.test.Sum.SumResponse> done) {
           impl.getSum(controller, request, done);
         }
 
       };
     }
 
     public static com.google.protobuf.BlockingService
         newReflectiveBlockingService(final BlockingInterface impl) {
       return new com.google.protobuf.BlockingService() {
         public final com.google.protobuf.Descriptors.ServiceDescriptor
             getDescriptorForType() {
           return getDescriptor();
         }
 
         public final com.google.protobuf.Message callBlockingMethod(
             com.google.protobuf.Descriptors.MethodDescriptor method,
             com.google.protobuf.RpcController controller,
             com.google.protobuf.Message request)
             throws com.google.protobuf.ServiceException {
           if (method.getService() != getDescriptor()) {
             throw new java.lang.IllegalArgumentException(
               "Service.callBlockingMethod() given method descriptor for " +
               "wrong service type.");
           }
           switch(method.getIndex()) {
             case 0:
               return impl.getSum(controller, (com.endpoint.test.Sum.SumRequest)request);
             default:
               throw new java.lang.AssertionError("Can't get here.");
           }
         }
 
         public final com.google.protobuf.Message
             getRequestPrototype(
             com.google.protobuf.Descriptors.MethodDescriptor method) {
           if (method.getService() != getDescriptor()) {
             throw new java.lang.IllegalArgumentException(
               "Service.getRequestPrototype() given method " +
               "descriptor for wrong service type.");
           }
           switch(method.getIndex()) {
             case 0:
               return com.endpoint.test.Sum.SumRequest.getDefaultInstance();
             default:
               throw new java.lang.AssertionError("Can't get here.");
           }
         }
 
         public final com.google.protobuf.Message
             getResponsePrototype(
             com.google.protobuf.Descriptors.MethodDescriptor method) {
           if (method.getService() != getDescriptor()) {
             throw new java.lang.IllegalArgumentException(
               "Service.getResponsePrototype() given method " +
               "descriptor for wrong service type.");
           }
           switch(method.getIndex()) {
             case 0:
               return com.endpoint.test.Sum.SumResponse.getDefaultInstance();
             default:
               throw new java.lang.AssertionError("Can't get here.");
           }
         }
 
       };
     }
 
     /**
      * <code>rpc getSum(.SumRequest) returns (.SumResponse);</code>
      */
     public abstract void getSum(
         com.google.protobuf.RpcController controller,
         com.endpoint.test.Sum.SumRequest request,
         com.google.protobuf.RpcCallback<com.endpoint.test.Sum.SumResponse> done);
 
     public static final
         com.google.protobuf.Descriptors.ServiceDescriptor
         getDescriptor() {
       return com.endpoint.test.Sum.getDescriptor().getServices().get(0);
     }
     public final com.google.protobuf.Descriptors.ServiceDescriptor
         getDescriptorForType() {
       return getDescriptor();
     }
 
     public final void callMethod(
         com.google.protobuf.Descriptors.MethodDescriptor method,
         com.google.protobuf.RpcController controller,
         com.google.protobuf.Message request,
         com.google.protobuf.RpcCallback<
           com.google.protobuf.Message> done) {
       if (method.getService() != getDescriptor()) {
         throw new java.lang.IllegalArgumentException(
           "Service.callMethod() given method descriptor for wrong " +
           "service type.");
       }
       switch(method.getIndex()) {
         case 0:
           this.getSum(controller, (com.endpoint.test.Sum.SumRequest)request,
             com.google.protobuf.RpcUtil.<com.endpoint.test.Sum.SumResponse>specializeCallback(
               done));
           return;
         default:
           throw new java.lang.AssertionError("Can't get here.");
       }
     }
 
     public final com.google.protobuf.Message
         getRequestPrototype(
         com.google.protobuf.Descriptors.MethodDescriptor method) {
       if (method.getService() != getDescriptor()) {
         throw new java.lang.IllegalArgumentException(
           "Service.getRequestPrototype() given method " +
           "descriptor for wrong service type.");
       }
       switch(method.getIndex()) {
         case 0:
           return com.endpoint.test.Sum.SumRequest.getDefaultInstance();
         default:
           throw new java.lang.AssertionError("Can't get here.");
       }
     }
 
     public final com.google.protobuf.Message
         getResponsePrototype(
         com.google.protobuf.Descriptors.MethodDescriptor method) {
       if (method.getService() != getDescriptor()) {
         throw new java.lang.IllegalArgumentException(
           "Service.getResponsePrototype() given method " +
           "descriptor for wrong service type.");
       }
       switch(method.getIndex()) {
         case 0:
           return com.endpoint.test.Sum.SumResponse.getDefaultInstance();
         default:
           throw new java.lang.AssertionError("Can't get here.");
       }
     }
 
     public static Stub newStub(
         com.google.protobuf.RpcChannel channel) {
       return new Stub(channel);
     }
 
     public static final class Stub extends com.endpoint.test.Sum.SumService implements Interface {
       private Stub(com.google.protobuf.RpcChannel channel) {
         this.channel = channel;
       }
 
       private final com.google.protobuf.RpcChannel channel;
 
       public com.google.protobuf.RpcChannel getChannel() {
         return channel;
       }
 
       public  void getSum(
           com.google.protobuf.RpcController controller,
           com.endpoint.test.Sum.SumRequest request,
           com.google.protobuf.RpcCallback<com.endpoint.test.Sum.SumResponse> done) {
         channel.callMethod(
           getDescriptor().getMethods().get(0),
           controller,
           request,
           com.endpoint.test.Sum.SumResponse.getDefaultInstance(),
           com.google.protobuf.RpcUtil.generalizeCallback(
             done,
             com.endpoint.test.Sum.SumResponse.class,
             com.endpoint.test.Sum.SumResponse.getDefaultInstance()));
       }
     }
 
     public static BlockingInterface newBlockingStub(
         com.google.protobuf.BlockingRpcChannel channel) {
       return new BlockingStub(channel);
     }
 
     public interface BlockingInterface {
       public com.endpoint.test.Sum.SumResponse getSum(
           com.google.protobuf.RpcController controller,
           com.endpoint.test.Sum.SumRequest request)
           throws com.google.protobuf.ServiceException;
     }
 
     private static final class BlockingStub implements BlockingInterface {
       private BlockingStub(com.google.protobuf.BlockingRpcChannel channel) {
         this.channel = channel;
       }
 
       private final com.google.protobuf.BlockingRpcChannel channel;
 
       public com.endpoint.test.Sum.SumResponse getSum(
           com.google.protobuf.RpcController controller,
           com.endpoint.test.Sum.SumRequest request)
           throws com.google.protobuf.ServiceException {
         return (com.endpoint.test.Sum.SumResponse) channel.callBlockingMethod(
           getDescriptor().getMethods().get(0),
           controller,
           request,
           com.endpoint.test.Sum.SumResponse.getDefaultInstance());
       }
 
     }
 
     // @@protoc_insertion_point(class_scope:SumService)
   }
 
   private static com.google.protobuf.Descriptors.Descriptor
     internal_static_SumRequest_descriptor;
   private static
     com.google.protobuf.GeneratedMessage.FieldAccessorTable
       internal_static_SumRequest_fieldAccessorTable;
   private static com.google.protobuf.Descriptors.Descriptor
     internal_static_SumResponse_descriptor;
   private static
     com.google.protobuf.GeneratedMessage.FieldAccessorTable
       internal_static_SumResponse_fieldAccessorTable;
 
   public static com.google.protobuf.Descriptors.FileDescriptor
       getDescriptor() {
     return descriptor;
   }
   private static com.google.protobuf.Descriptors.FileDescriptor
       descriptor;
   static {
     java.lang.String[] descriptorData = {
       "\n\rsumcode.proto\",\n\nSumRequest\022\016\n\006family\030" +
       "\001 \002(\t\022\016\n\006column\030\002 \002(\t\"\035\n\013SumResponse\022\016\n\003" +
       "sum\030\001 \002(\003:\001021\n\nSumService\022#\n\006getSum\022\013.S" +
       "umRequest\032\014.SumResponseB \n\021com.endpoint." +
       "testB\003SumH\001\210\001\001\240\001\001"
     };
     com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
       new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
         public com.google.protobuf.ExtensionRegistry assignDescriptors(
             com.google.protobuf.Descriptors.FileDescriptor root) {
           descriptor = root;
           internal_static_SumRequest_descriptor =
             getDescriptor().getMessageTypes().get(0);
           internal_static_SumRequest_fieldAccessorTable = new
             com.google.protobuf.GeneratedMessage.FieldAccessorTable(
               internal_static_SumRequest_descriptor,
               new java.lang.String[] { "Family", "Column", });
           internal_static_SumResponse_descriptor =
             getDescriptor().getMessageTypes().get(1);
           internal_static_SumResponse_fieldAccessorTable = new
             com.google.protobuf.GeneratedMessage.FieldAccessorTable(
               internal_static_SumResponse_descriptor,
               new java.lang.String[] { "Sum", });
           return null;
         }
       };
     com.google.protobuf.Descriptors.FileDescriptor
       .internalBuildGeneratedFileFrom(descriptorData,
         new com.google.protobuf.Descriptors.FileDescriptor[] {
         }, assigner);
   }
 
   // @@protoc_insertion_point(outer_class_scope)
 }

2> 编写服务器端的代码

 package com.endpoint.test;
 
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import org.apache.hadoop.hbase.Cell;
 import org.apache.hadoop.hbase.CellUtil;
 import org.apache.hadoop.hbase.Coprocessor;
 import org.apache.hadoop.hbase.CoprocessorEnvironment;
 import org.apache.hadoop.hbase.client.Scan;
 import org.apache.hadoop.hbase.coprocessor.CoprocessorException;
 import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
 import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
 import org.apache.hadoop.hbase.protobuf.ResponseConverter;
 import org.apache.hadoop.hbase.regionserver.InternalScanner;
 import org.apache.hadoop.hbase.util.Bytes;
 import com.endpoint.test.Sum.SumRequest;
 import com.endpoint.test.Sum.SumResponse;
 import com.endpoint.test.Sum.SumService;
 import com.google.protobuf.RpcCallback;
 import com.google.protobuf.RpcController;
 import com.google.protobuf.Service;
 
 public class SumEndPoint extends SumService implements Coprocessor,CoprocessorService{
 
     private RegionCoprocessorEnvironment env;   // 定义环境
     @Override
     public Service getService() {
 
         return this;
     }
 
     @Override
     public void start(CoprocessorEnvironment env) throws IOException {
          if (env instanceof RegionCoprocessorEnvironment) {
                 this.env = (RegionCoprocessorEnvironment)env;
             } else {
                 throw new CoprocessorException("no load region");
             }  
 
     }
 
     @Override
     public void stop(CoprocessorEnvironment env) throws IOException {
 
     }
 
     @Override
     public void getSum(RpcController controller, SumRequest request, RpcCallback<SumResponse> done) {
 
         // 设置扫描对象
         Scan scan = new Scan();
         scan.addFamily(Bytes.toBytes(request.getFamily()));
         scan.addColumn(Bytes.toBytes(request.getFamily()), Bytes.toBytes(request.getColumn()));  
 
         // 定义变量
         SumResponse response = null;
         InternalScanner scanner = null;  
 
         // 扫描每个region,取值后求和
         try {
             scanner = env.getRegion().getScanner(scan);
             List<Cell> results = new ArrayList<Cell>();
             boolean hasMore = false;
             Long sum = 0L;
             do {
                 hasMore = scanner.next(results);
                 for (Cell cell : results) {
                     sum += Long.parseLong(new String(CellUtil.cloneValue(cell)));
                 }
                 results.clear();
             } while (hasMore);
             // 设置返回结果
             response = SumResponse.newBuilder().setSum(sum).build();
         } catch (IOException e) {
             ResponseConverter.setControllerException(controller, e);
         } finally {
             if (scanner != null) {
                 try {
                     scanner.close();
                 } catch (IOException e) {
                     //e.printStackTrace();
                 }
             }
         }
         // 将rpc结果返回给客户端
         done.run(response);  
 
     }
 
 }

3> 客户端测试代码

 package com.endpoint.test;
 
 import java.io.IOException;
 import java.util.Map;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.hbase.HBaseConfiguration;
 import org.apache.hadoop.hbase.TableName;
 import org.apache.hadoop.hbase.client.Connection;
 import org.apache.hadoop.hbase.client.ConnectionFactory;
 import org.apache.hadoop.hbase.client.HTable;
 import org.apache.hadoop.hbase.client.coprocessor.Batch;
 import org.apache.hadoop.hbase.ipc.BlockingRpcCallback;
 import com.endpoint.test.Sum.SumRequest;
 import com.endpoint.test.Sum.SumResponse;
 import com.endpoint.test.Sum.SumService;
 import com.google.protobuf.ServiceException;
 
 public class TestClient {
 
     public static void main(String[] args) throws Exception {
 
             // 配置HBse
             Configuration conf = HBaseConfiguration.create();
             conf.set("hbase.zookeeper.quorum", "master,data1,data2");
             conf.set("hbase.zookeeper.property.clientPort", "2181");
             conf.setLong("hbase.rpc.timeout", 600000);
             System.setProperty("hadoop.home.dir", "C:/hadoopfiles/hadoop-common-2.2.0-bin-master");
 
             // 建立一个数据库的连接
             Connection conn = ConnectionFactory.createConnection(conf);
             // 获取表
             HTable table = (HTable) conn.getTable(TableName.valueOf("etable"));  
 
             long sum = 0L;                
 
             // 设置请求对象
             final SumRequest request = SumRequest.newBuilder().setFamily("cf").setColumn("value").build();  
 
             try {
                 // 获得返回值
                 Map<byte[], Long> result = table.coprocessorService(SumService.class, null, null,
                         new Batch.Call<SumService, Long>() {  
 
                             @Override
                             public Long call(SumService service) throws IOException {
                                 BlockingRpcCallback<SumResponse> rpcCallback = new BlockingRpcCallback<SumResponse>();
                                 service.getSum(null, request, rpcCallback);
                                 SumResponse response = (SumResponse) rpcCallback.get();
                                 return response.hasSum() ? response.getSum() : 0L;
                             }
                 });
                 // 将返回值进行迭代相加
                 for (Long v : result.values()) {
                     sum += v;
                 }
                 // 结果输出
                 System.out.println("sum: " + sum);                        
 
             } catch (ServiceException e) {
                 e.printStackTrace();
             }catch (Throwable e) {
                 e.printStackTrace();
             }
             table.close();
             conn.close();  
 
     }
 
 }

System.setProperty("hadoop.home.dir", "C:/hadoopfiles/hadoop-common-2.2.0-bin-master"); 这句代码是防错误用的,不具有实际意义,在hadoop-common-2.2.0-bin-master下建立bin目录放一个winutils.exe文件即可,否则会出现提示“Could not locate executable null\bin\winutils.exe in the Hadoop binaries”

此外,需要在windows下设置一下hosts文件,因为conf.set("hbase.zookeeper.quorum", "master,data1,data2");

4> 使用Endpoint协处理器

将上面的Sum类文件与用于服务端的SumEndPoint 类文件打包上传到服务器

chown hadoop:hadoop datacode.jar
chmod g+w  datacode.jar 

先改一下权限,之后

hadoop fs -copyFromLocal sumtest.jar /input/

下面是要使用协处理器的hbase表        

要将协处理器加载到这个表上

disable 'etable'
# 包名.类名|权重 com.endpoint.test.SumEndPoint|100
alter'etable',METHOD =>'table_att','coprocessor' =>'/input/sumcode.jar|com.endpoint.test.SumEndPoint|100'
enable 'etable'

 

  1. 包名.类名|权重 com.endpoint.test.SumEndPoint|100
    # 这样也是可以的,但是在集群变换主节点的情况下,不是很好
    # alter'etable',METHOD =>'table_att','coprocessor' =>'hdfs://192.168.1.215:9000/input/sumcode.jar|com.endpoint.test.SumEndPoint|100'

    此外,值得注意的一点,在集群中,最好在hbase-site.xml中设置以下属性

    <property>
            <name>hbase.coprocessor.abortonerror</name>
            <value>false</value>
    </property> 

    设置为false目的在于提高容错性,如果这个属性没有设置为false,则在上传的jar包存在错误的情况下,会导致表不能enable或disable,从而导致集群中的这张表无法使用,甚至会影响到其他表。

  2. 表无法使用,甚至会影响到其他表。

    在windows中的客户端运行客户端的代码,结果如下:

     2、Observer实例
    这个是一个二级索引实例,即假定在initialtable表中的数据格式是这样的

    row1    E   151
    row2    Y   158

    在向initialtable表中写入数据时,自动将以下数据写入indextable表作为二级索引,indextable第二列成为indextable的键

    Y    158

    1> 编写服务端代码

     package com.observer.test;
     
     import java.io.IOException;
     import java.util.List;
     import org.apache.hadoop.hbase.Cell;
     import org.apache.hadoop.hbase.CellUtil;
     import org.apache.hadoop.hbase.TableName;
     import org.apache.hadoop.hbase.client.Durability;
     import org.apache.hadoop.hbase.client.HTableInterface;
     import org.apache.hadoop.hbase.client.Put;
     import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
     import org.apache.hadoop.hbase.coprocessor.ObserverContext;
     import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
     import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
     import org.apache.hadoop.hbase.util.Bytes;
     
     public class TestObserver extends BaseRegionObserver {
         @Override
         public void postPut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit, Durability durability)
                 throws IOException {
             // indextable作为二级索引表
             HTableInterface table = e.getEnvironment().getTable(TableName.valueOf("indextable"));
             // 获取值
             List<Cell> cellList1 = put.get(Bytes.toBytes("cf"), Bytes.toBytes("name"));
             List<Cell> cellList2 = put.get(Bytes.toBytes("cf"), Bytes.toBytes("value"));
             // 写入数据
             for (Cell cell1 : cellList1) {
                 // 原表的列cf:name的值作为indextable的rowkey,添加行
                 Put indexPut = new Put(CellUtil.cloneValue(cell1));
                 for (Cell cell2 : cellList2) {
                     // 原表的列cf:value的值作为indextable表中列cf:value的值 。
                     indexPut.add(Bytes.toBytes("cf"), Bytes.toBytes("value"), CellUtil.cloneValue(cell2));
                 }  
     
                 table.put(indexPut);
             }  
     
             table.close();
         }
     
     }

    2> 编写客户段代码

     package com.observer.test;
     
     import java.io.IOException;
     
     import org.apache.hadoop.conf.Configuration;
     import org.apache.hadoop.hbase.HBaseConfiguration;
     import org.apache.hadoop.hbase.TableName;
     import org.apache.hadoop.hbase.client.Connection;
     import org.apache.hadoop.hbase.client.ConnectionFactory;
     import org.apache.hadoop.hbase.client.HTable;
     import org.apache.hadoop.hbase.client.Put;
     import org.apache.hadoop.hbase.util.Bytes;
     
     public class DataClient {
     
         public static void main(String[] args) throws IOException {
             //配置
             Configuration conf = HBaseConfiguration.create();
             conf.set("hbase.zookeeper.quorum", "master,data1,data2");
             conf.set("hbase.zookeeper.property.clientPort", "2181");
             //连接
             Connection conn = ConnectionFactory.createConnection(conf);
             HTable table = (HTable) conn.getTable(TableName.valueOf("initialtable"));
             // 写入数据
             Put put = new Put(Bytes.toBytes("row01"));
             put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes("E"));
             put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("value"), Bytes.toBytes("151"));
             table.put(put);
             // 关闭资源
             table.close();
             conn.close();  
     
         }
     
     }

    3> 创建需要的表

    4> 加载协处理器
    将服务端代码打包上传集群服务器的hdfs上

    chown hadoop:hadoop datacode.jar
    chmod g+w  datacode.jar
    hadoop dfs -put datacode.jar /input/
    

     之后,将协处理器加载到初始表中

    disable 'initialtable'
    alter'initialtable',METHOD =>'table_att','coprocessor' =>'/input/datacode.jar|com.observer.test.TestObserver|100'
    enable 'initialtable'

    5> 执行客户端代码,显示结果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/683066.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MATLAB 之 对话框设计实例和菜单设计

这里写目录标题 一、对话框设计实例1. 数值转化2. 图形演示 二、菜单设计1. 建立用户菜单2. 菜单对象常用属性3. 快捷菜单 一、对话框设计实例 在上一篇博客当中&#xff0c;我们介绍了控件的基本操作&#xff0c;这是建立对话框的基础。下面我们举两个例子&#xff0c;用以说…

软件测试工程师最常用的Linux系统命令大全(汇总)

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 cd命令 这是一个…

最新导则下生态环评报告编制技术

根据生态环评内容庞杂、综合性强的特点&#xff0c;依据生态环评最新导则&#xff0c;将内容分为4大篇章(报告篇、制图篇、指数篇、综合篇)、 10大专题(生态环评报告编制、土地利用图的制作、植被类型及植被覆盖度图的制作、物种适宜生境分布图的制作、生物多样性测定、生物量…

开窗函数之聚合、取特定值、排名

一&#xff0c; 聚合开窗函数sum(score) over(partition by name ) 二&#xff0c;开窗函数之first_value&#xff0c;last_value&#xff0c;lead&#xff0c;lag 三&#xff0c;排名开窗函数ROW_NUMBER、DENSE_RANK、RANK 一&#xff0c;开窗函数的语法 开窗函数的语法为&am…

Pinia理解【Vue3】

什么是Pinia Pinia是Vue的专属的最新状态管理库&#xff0c;是Vuex状态管理工具的替代品 优势&#xff1a; 提供了更加简单的API (去掉了mutation)提供符合组合式风格的API(和Vue3新语法统一)去掉了 modules 的概念&#xff0c;每一个 store 都是一个独立的模块搭配 TypeScr…

RabbitMQ Exchange类型和工作模式介绍

RabbitMQ Exchange类型和工作模式介绍 一RabbitMQ Exchange类型1.1.Fanout1.2.Direct1.3.Topic1.4.Headers 二 RabbitMQ 工作模式介绍2.1.work工作模式(资源的竞争)2.2.publish/subscribe发布订阅(共享资源)2.3.routing路由模式应用--direct交换器 2.4.topic 主题模式(路由模式…

一键轻松造数据:通过Postman实现表单提交

一、原始需求的诞生 在测试的过程中&#xff0c;需要大量的表单。于是我选择了通过postman发送表单提交的接口来造数据。 如上图所示&#xff0c;表单提交接口所需的参数以及请求体中需模拟的IP地址。参数为 {{}} 的表示需要不同的实参&#xff0c;至于原因就不在这里赘述了。如…

618手机大战:各大品牌花式秀战报,但难掩冷淡行情

在手机出货量持续下行的态势下&#xff0c;各大手机厂商普遍对618这个年中大促寄予厚望&#xff0c;希望通过各种促销手段&#xff0c;扭转销售颓势。 比如&#xff0c;今年5月下旬&#xff0c;小米、荣耀、OPPO、vivo等厂商就已经开启了降价、分期免息等优惠活动&#xff0c;…

Vue3自定义指令实现按钮权限

一、需求前提 登录成功后&#xff0c;后端直接返回了用户的所有权限&#xff08;路由权限按钮权限&#xff09;&#xff0c;在已经实现菜单权限的基础上&#xff0c;实现每个页面的按钮权限&#xff0c;树形数据结构如下&#xff1a; { "roles": ["admin&q…

嵌入式实时操作系统的设计与开发New(六)

aCoral的优先级与数字大小成反比&#xff0c;即&#xff1a;数字越大&#xff0c;优先级越低。 #define MAX_PRIO_NUM ((CFG_MAX_THREAD1) & 0xff) #define MINI_PRIO CFG_MAX_THREAD //最低优先级40typedef enum{ACORAL_INIT_PRIO; //init线程独有的0优先级ACORAL_MAX_PR…

如何刷新 DNS 缓存 (macOS, Linux, Windows)

如何刷新 DNS 缓存 (macOS, Linux, Windows) Unix Linux Windows 如何刷新 DNS 缓存 (macOS, FreeBSD, RHEL, CentOS, Debian, Ubuntu, Windows) 请访问原文链接&#xff1a;https://sysin.org/blog/how-to-flush-dns-cache/&#xff0c;查看最新版。原创作品&#xff0c;转载…

论文解读|基于平面双关节机器人的相机姿态分析与评估

原创 | 文 BFT机器人 01 研究内容 论文的主要研究内容是基于平面双关节机器人的相机姿态分析和评估。研究旨在分析相机的位置调整和一般数据分析&#xff0c;讨论人体姿势的平衡、关节运动的控制以及相机速率的估计和控制。 通过有限相机技术的应用&#xff0c;有效解决平面摄影…

【虚拟机数据恢复】XenServer虚拟机磁盘数据被破坏的数据恢复案例

虚拟机数据恢复环境&#xff1a; 一台某品牌720服务器&#xff0c;4块STAT硬盘通过RAID卡组建raid10磁盘阵列。部署的XenServer虚拟化平台Windows Server操作系统&#xff0c;共两个虚拟磁盘&#xff1a;数据盘系统盘。服务器作为Web服务器使用&#xff0c;上层部署ASP SQL Se…

Chrome插件开发_V3_浏览器扩展插件基础教程

文章目录 一、简介二、核心介绍三、自定义页面背景色三、设置页面背景图&#xff08;web_accessible_resources&#xff09;四、设置徽章&#xff08;Badge&#xff09;五、桌面通知六、消息通信七、自定义右键菜单&#xff08;添加、更新、删除&#xff09;八、Omnibox九、浏览…

JVM基础知识

JVM 一次编译终身运行1.1 JVM和java的体系结构1.1.1 虚拟机与JAVA虚拟机1.1.2 JVM的位置1.1.3 JVM的整体执行流程1.1.4 JAVA代码的执行流程1.1.5 JVM架构模型1.1.6 JVM的生命周期1.1.7 Sun Classic Vm1.1.8 Exact VM1.1.9 Hotspot VM1.1.10 BEA的JRockit1.1.11 IBM的 J91.1.12 …

云渲染是什么?如何挑选云渲染平台

在影视动画、建筑设计、游戏开发等领域&#xff0c;渲染是一个非常重要的环节&#xff0c;它可以将场景、模型、纹理、材质等元素综合起来&#xff0c;生成逼真的图像或视频。然而&#xff0c;渲染也是一个非常耗时和耗能的过程&#xff0c;它需要大量的计算资源和硬件设备&…

Intel base instruction -- Jcc

检查EFLAGS寄存器中一个或多个状态标志&#xff08;CF、of、PF、SF和ZF&#xff09;的状态&#xff0c;如果这些标志处于指定状态&#xff08;条件&#xff09;&#xff0c;则执行跳转到目标操作数指定的目标指令。条件代码&#xff08;cc&#xff09;与每个指令相关联&#xf…

实用干货-汇总篇

_ 实用干货 _ 11.实用干货-基因&基因组知识回顾 (qq.com)22.实用干货—解惑NGS可能引入的错误突变 (qq.com)33.临床肿瘤NGS的常规检测流程 (qq.com)44.实用干货—DNA甲基化相关知识点整理 (qq.com)55.实用干货-NGS的QC质控和突变结果复核 (qq.com)65.实用干货-你可能没…

patch 报错 can‘t find file to patch at input line 4

错误现象&#xff1a; 解决 -p3 patch -p3 < ../speccpu2006-kylinv10-aarch64.patch

问题总结,web自动化测试元素无法操作?shadowDOM节点元素解决......

前言 web自动化遇到shadowDOM你会操作吗&#xff1f; 之前在做web自动化的时候&#xff0c;发现页面上有些元素&#xff0c;在selenium中无法通过xpath来定位&#xff0c;各种原因找了半天都没找到解决方案&#xff0c;最后发现元素在一个叫做shadow-root的节点下面&#xff…