Updated on 2022-06-01 GMT+08:00

Creating the Connection Object

Function Description

HBase creates a Connection object using the ConnectionFactory.createConnection(configuration) method. The transferred parameter is the Configuration created in the previous step.

Connection encapsulates the connections between underlying applications and servers and ZooKeeper. Connection is instantiated using the ConnectionFactory class. Creating Connection is a heavyweight operation. Connection is thread-safe. Therefore, multiple client threads can share one Connection.

In a typical scenario, a client program uses a Connection, and each thread obtains its own Admin or Table instance and invokes the operation interface provided by the Admin or Table object. You are not advised to cache or pool Table and Admin. The lifecycle of Connection is maintained by invokers who can release resources by invoking close().

Sample Code

The following code snippet is an example of creating a Connection:

private TableName tableName = null;
private Configuration conf = null;
private Connection conn = null;
public static final String TABLE_NAME = "hbase_sample_table";

public HBaseExample(Configuration conf) throws IOException {
  this.conf = conf;
  this.tableName = TableName.valueOf(TABLE_NAME);
  this.conn = ConnectionFactory.createConnection(conf);
}
  1. Example code involves many operations, such as creating, querying, and deleting tables. Only testCreateTable and dropTable are used as an example in this section. For details, see examples in the specific section.
  2. The Admin object required by table creation is obtained from the Connection object.
  3. Avoid invoking login code repeatedly.