新手尝试HBase,练手java API 的简单put get delete 操作。
考虑到 Table 的线程不安全,尝试使用HConnectionManager获取 HConnection,进行一系列CRUD。
中间遇到了一个小问题,记录下,方便以后回顾,也可以帮助其他初学者。
首先用
HConnection hConn = HConnectionManager.getConnection(conf);
HTableInterface hTableInterface = hConn.getTable(tableName);
//tableName 为String
获取了HTableInterface ,执行操作并hTableInterface.flushCommits();
后报出异常 Exception in thread “main” java.io.IOException: The connection has to be unmanaged.
跟踪HConnectionManager源码,查看到
@Override
public HTableInterface getTable(byte[] tableName, ExecutorService pool) throws IOException {
if (managed) {
throw new IOException("The connection has to be unmanaged.");
}
return new HTable(tableName, this, pool);
}
由于managed 是收管理的 抛出IO异常
而这个boolean 类型的在getConnection(conf);阶段就已经被设置成了true
public static HConnection getConnection(Configuration conf)
throws ZooKeeperConnectionException {
HConnectionKey connectionKey = new HConnectionKey(conf);
synchronized (HBASE_INSTANCES) {
HConnectionImplementation connection = HBASE_INSTANCES.get(connectionKey);
if (connection == null) {
connection = new HConnectionImplementation(conf, true, null);
HBASE_INSTANCES.put(connectionKey, connection);
} else if (connection.isClosed()) {
HConnectionManager.deleteConnection(connectionKey, true);
connection = new HConnectionImplementation(conf, true, null);
HBASE_INSTANCES.put(connectionKey, connection);
}
connection.incCount();
return connection;
}
}
所以我尝试自己 new HConnectionImplementation 但是线程池不确定 所以观望了一会儿
发现Manager类中还有一个createHConnection,源码如下
public static HConnection createConnection(Configuration conf)
throws ZooKeeperConnectionException {
return new HConnectionImplementation(conf, false, null);
}
异常解决。可以不用担心线程是否安全,放心操作HBase 的 CRUD了。