咱们先看HConnection的getTable方法描述:html
HTableInterface getTable(String tableName) throws IOException
Retrieve an HTableInterface implementation for access to a table. The returned HTableInterface is not thread safe, a new instance should be created for each using thread. This is a lightweight operation, pooling or caching of the returned HTableInterface is neither required nor desired. Note that the HConnection needs to be unmanaged (created withHConnectionManager.createConnection(Configuration)
).java
tableName
-
IOException
而后再联想到只要HTable使用的Configuration是同一个,那么它们必定是共用一个HConnection的,HConnection才是HBase客户端到Hbase集群的真正的链接。apache
再想一想HTablePool的做用,无非就是HTable的链接池,里面维护的HTable应该来讲都是使用的同一个HConnecion。api
既然HTable的建立是轻量级的,使用同一个Confuguration的HTable都会共用一个HConnection,那么HTablePool就显得那么多余!缓存
因此Hbase抛弃了HTablePool,咱们惟一要作的就是保证HConnection实例是惟一的,全局共享的。而后针对HTableInterface对象最好在每次操做HBase表的时候根据HConnection对象来从新建立,使用完成以后及时关闭便可!安全
经过HConnection的getTable()方法就可以获取到用户操做HBase表的HTableInterface对象了。oracle
下面是一个使用HConnection的getTable()方法获取HTableInterface对象的例子:oop
public void addUser(User user) throws IOException { HTableInterface usersTable = conn.getTable(TABLE_NAME); Put put = makePut(user); usersTable.put(put); usersTable.close(); log.info("Add a User:"+user.name+" successfully"); }
至于HConnection对象如何建立,HBase推荐使用的方法是:ui
public static HConnection createConnection(org.apache.hadoop.conf.Configuration conf) throws IOException
conf
instance.
Note: This bypasses the usual HConnection life cycle management done bygetConnection(Configuration)
. The caller is responsible for callingCloseable.close()
on the returned connection instance. This is the recommended way to create HConnections. HConnection connection = HConnectionManager.createConnection(conf); HTableInterface table = connection.getTable("mytable"); table.get(...); ... table.close(); connection.close();
this
conf
- configuration
conf
ZooKeeperConnectionException
IOException
下面代码是我按照单例模式维护HConnection对象的例子:
public class HBaseUtils { private static final String QUORUM = "192.168.1.100"; private static final String CLIENTPORT = "2181"; private static Configuration conf = null; private static HConnection conn = null; /** * 获取全局惟一的Configuration实例 * @return */ public static synchronized Configuration getConfiguration() { if(conf == null) { conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum", QUORUM); conf.set("hbase.zookeeper.property.clientPort", CLIENTPORT); } return conf; } /** * 获取全局惟一的HConnection实例 * @return * @throws ZooKeeperConnectionException */ public static synchronized HConnection getHConnection() throws ZooKeeperConnectionException { if(conn == null) { /* * * 建立一个HConnection * HConnection connection = HConnectionManager.createConnection(conf); * HTableInterface table = connection.getTable("mytable"); * table.get(...); ... * table.close(); * connection.close(); * */ conn = HConnectionManager.createConnection(getConfiguration()); } return conn; } }
以上属于我的看法,若是有什么疑问和指教,欢迎指正。