Java連接HBase的正確方法及Connection創建步驟與詳解

Java連接HBase的正確方法及Connection創建步驟與詳解

HBASE的連接不像其他傳統關係型數據庫連接需要維護連接池。HBASE連接若使用錯誤則會導致隨時間推移程序創建的TCP連接過多,導致HBASE連接失敗。

本文介紹HBase客戶端的Connection對象與Socket連接的關係並且給出Connection的正確用法。

Connection是什麼?

常見的使用Connection的錯誤方法有:

  1. 自己實現一個Connection對象的資源池,每次使用都從資源池中取出一個Connection對象;
  2. 每個線程一個Connection對象。
  3. 每次訪問HBase的時候臨時創建一個Connection對象,使用完之後調用close關閉連接。

從這些做法來看,顯然是把Connection對象當成了單機數據庫裏面的連接對象來用了。然而作爲分佈式數據庫,HBase客戶端需要和多個服務器中的不同服務角色建立連接,所以HBase客戶端中的Connection對象並不是簡單對應一個socket連接。HBase的API文檔當中對Connection的定義是:

A cluster connection encapsulating lower level individual connections to actual servers and a connection to zookeeper.

我們知道,HBase clinet要連接三個不同的服務角色:

  1. Zookeeper:主要用於獲得meta-region位置,集羣Id、master等信息。
  2. HBase Master:主要用於執行HBaseAdmin接口的一些操作,例如建表等。
  3. HBase RegionServer:用於讀、寫數據。

下圖簡單示意了客戶端與服務器交互的步驟:


HBase客戶端的Connection包含了對以上三種Socket連接的封裝。Connection對象和實際的Socket連接之間的對應關係如下圖:

HBase客戶端代碼真正對應Socket連接的是RpcConnection對象。HBase使用PoolMap這種數據結構來存儲客戶端到HBase服務器之間的連接。PoolMap封裝ConcurrentHashMap的結構,key是ConnectionId(封裝服務器地址和用戶ticket),value是一個RpcConnection對象的資源池。

當HBase需要連接一個服務器時,首先會根據ConnectionId找到對應的連接池,然後從連接池中取出一個連接對象。

HBase提供三種資源池的實現,分別是Reusable,RoundRobin和ThreadLocal。具體實現可以通過hbase.client.ipc.pool.type配置項指定,默認爲Reusable。連接池的大小也可以通過hbase.client.ipc.pool.size配置項指定,默認爲1。

連接HBase的正確姿勢

從以上分析不難得出,在HBase中Connection類已經實現對連接的管理功能,所以不需要在Connection之上再做額外的管理。另外,Connection是線程安全的,然而Table和Admin則不是線程安全的,因此正確的做法是一個進程共用一個Connection對象,而在不同的線程中使用單獨的Table和Admin對象。

//所有進程共用一個Connection對象
connection=ConnectionFactory.createConnection(config);
        ...
//每個線程使用單獨的Table對象
Table table = connection.getTable(TableName.valueOf("test"));
try {
    ...
} finally {
    table.close();
}

Connection 創建連接步驟及代碼解析

HBase客戶端默認的是連接池大小是1,也就是每個RegionServer 1個連接。如果應用需要使用更大的連接池或指定其他的資源池類型,也可以通過修改配置實現。

Connection創建RpcClient的核心入口:

/**
  * constructor
  * @param conf Configuration object
  */
ConnectionImplementation(Configuration conf,
                    ExecutorService pool, User user) throws IOException {
    ...
    try {
      ...
      this.rpcClient = RpcClientFactory.createClient(this.conf, this.clusterId, this.metrics);
      ...
    } catch (Throwable e) {
      // avoid leaks: registry, rpcClient, ...
      LOG.debug("connection construction failed", e);
      close();
      throw e;
    }
}

RpcClient使用PoolMap數據結構存儲客戶端到HBase服務器之間的連接映射,PoolMap封裝ConcurrentHashMap結構,其中key是ConnectionId[new ConnectionId(ticket, md.getService().getName(), addr)],value是RpcConnection對象的資源池。

protected final PoolMap<ConnectionId, T> connections;

/**
  * Construct an IPC client for the cluster <code>clusterId</code>
  * @param conf configuration
  * @param clusterId the cluster id
  * @param localAddr client socket bind address.
  * @param metrics the connection metrics
  */
public AbstractRpcClient(Configuration conf, String clusterId, SocketAddress localAddr,
      MetricsConnection metrics) {
    ...
    this.connections = new PoolMap<>(getPoolType(conf), getPoolSize(conf));
    ...
}

當HBase需要連接一個服務器時,首先會根據ConnectionId找到對應的連接池,然後從連接池中取出一個連接對象,獲取連接的核心實現:

/**
  * Get a connection from the pool, or create a new one and add it to the pool. Connections to a
  * given host/port are reused.
  */
private T getConnection(ConnectionId remoteId) throws IOException {
    if (failedServers.isFailedServer(remoteId.getAddress())) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Not trying to connect to " + remoteId.address
            + " this server is in the failed servers list");
      }
      throw new FailedServerException(
          "This server is in the failed servers list: " + remoteId.address);
    }
    T conn;
    synchronized (connections) {
      if (!running) {
        throw new StoppedRpcClientException();
      }
      conn = connections.get(remoteId);
      if (conn == null) {
        conn = createConnection(remoteId);
        connections.put(remoteId, conn);
      }
      conn.setLastTouched(EnvironmentEdgeManager.currentTime());
    }
    return conn;
 }

連接池根據ConnectionId獲取不到連接則創建RpcConnection的具體實現:

PS: HBASE2.0後使用基於Netty框架建立RPC連接,2.0之前使用的還是基於Socket原生連接,此部分源碼可能不同版本不一樣。

NettyRpcServer
HBase2.0 開始默認使用NettyRpcServer
使用Netty替代HBase原生的RPC server,大大提升了HBaseRPC的吞吐能力,降低了延遲

protected NettyRpcConnection createConnection(ConnectionId remoteId) throws IOException {
    return new NettyRpcConnection(this, remoteId);
}

NettyRpcConnection(NettyRpcClient rpcClient, ConnectionId remoteId) throws IOException {
    super(rpcClient.conf, AbstractRpcClient.WHEEL_TIMER, remoteId, rpcClient.clusterId,
        rpcClient.userProvider.isHBaseSecurityEnabled(), rpcClient.codec, rpcClient.compressor);
    this.rpcClient = rpcClient;
    byte connectionHeaderPreamble = getConnectionHeaderPreamble();
    this.connectionHeaderPreamble =
        Unpooled.directBuffer(connectionHeaderPreamble.length).writeBytes(connectionHeaderPreamble);
    ConnectionHeader header = getConnectionHeader();
    this.connectionHeaderWithLength = Unpooled.directBuffer(4 + header.getSerializedSize());
    this.connectionHeaderWithLength.writeInt(header.getSerializedSize());
    header.writeTo(new ByteBufOutputStream(this.connectionHeaderWithLength));
}

protected RpcConnection(Configuration conf, HashedWheelTimer timeoutTimer, ConnectionId remoteId,
      String clusterId, boolean isSecurityEnabled, Codec codec, CompressionCodec compressor)
      throws IOException {
    if (remoteId.getAddress().isUnresolved()) {
      throw new UnknownHostException("unknown host: " + remoteId.getAddress().getHostName());
    }
    this.timeoutTimer = timeoutTimer;
    this.codec = codec;
    this.compressor = compressor;
    this.conf = conf;

    UserGroupInformation ticket = remoteId.getTicket().getUGI();
    SecurityInfo securityInfo = SecurityInfo.getInfo(remoteId.getServiceName());
    this.useSasl = isSecurityEnabled;
    Token<? extends TokenIdentifier> token = null;
    String serverPrincipal = null;
    if (useSasl && securityInfo != null) {
      AuthenticationProtos.TokenIdentifier.Kind tokenKind = securityInfo.getTokenKind();
      if (tokenKind != null) {
        TokenSelector<? extends TokenIdentifier> tokenSelector = AbstractRpcClient.TOKEN_HANDLERS
            .get(tokenKind);
        if (tokenSelector != null) {
          token = tokenSelector.selectToken(new Text(clusterId), ticket.getTokens());
        } else if (LOG.isDebugEnabled()) {
          LOG.debug("No token selector found for type " + tokenKind);
        }
      }
      String serverKey = securityInfo.getServerPrincipal();
      if (serverKey == null) {
        throw new IOException("Can't obtain server Kerberos config key from SecurityInfo");
      }
      serverPrincipal = SecurityUtil.getServerPrincipal(conf.get(serverKey),
        remoteId.address.getAddress().getCanonicalHostName().toLowerCase());
      if (LOG.isDebugEnabled()) {
        LOG.debug("RPC Server Kerberos principal name for service=" + remoteId.getServiceName()
            + " is " + serverPrincipal);
      }
    }
    this.token = token;
    this.serverPrincipal = serverPrincipal;
    if (!useSasl) {
      authMethod = AuthMethod.SIMPLE;
    } else if (token != null) {
      authMethod = AuthMethod.DIGEST;
    } else {
      authMethod = AuthMethod.KERBEROS;
    }

    // Log if debug AND non-default auth, else if trace enabled.
    // No point logging obvious.
    if ((LOG.isDebugEnabled() && !authMethod.equals(AuthMethod.SIMPLE)) ||
        LOG.isTraceEnabled()) {
      // Only log if not default auth.
      LOG.debug("Use " + authMethod + " authentication for service " + remoteId.serviceName
          + ", sasl=" + useSasl);
    }
    reloginMaxBackoff = conf.getInt("hbase.security.relogin.maxbackoff", 5000);
    this.remoteId = remoteId;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章