在web应用中,如果我们之间使用HTable来操作hbase, 那么在创建连接和关闭连接的时候,一定会浪费资源。那么HBase提供了一个连接池的技术。
主要涉及到的类和接口包括:HConnection, HConnectionManager, HTableInterface, ExecutorService(jdk提供的线程池)四个。
其中,HConnection就是hbase封装好的hbase连接池。
HConnectionManager是管理连接池的一个类。
HTableInterface是在类HTable的基础上进行的一个接口抽象。
ExecutorService是jdk的线程池对象。
static void testUseHbaseConnectionPool(Configuration conf) throws IOException { //创建两个线程进行操作 ExecutorService threads = Executors.newFixedThreadPool(2); HConnection pool = HConnectionManager.createConnection(conf, threads); HTableInterface hTable = pool.getTable("users"); try{ testPut(hTable); testGet(hTable); testDelete(hTable); testScan(hTable); }finally { hTable.close(); // 每次htable操作完关闭,其实是放到pool中 pool.close(); // 最终时候的关闭 } }