java - Spring HbaseTemplate 保持连接活跃
问题描述
我设法使用以下方法集成Hbase
到Spring
应用程序中HbaseTemplate
:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ItemRepositoryImpl implements ItemRepository {
@Autowired
private HbaseTemplate hbaseTemplate;
@Override
public List<Item> findAll() {
Scan scan = new Scan();
scan.addColumn(CF, CQ);
hbaseTemplate.find("TABLE_NAME", scan, (result, rowNum) -> {
return new Item(...)
});
}
}
但是,每次运行时都会打开与 Hbase 的连接findAll()
(并在之后关闭)。我在某处读到保持连接活动的方法是使用Connection
和Table
调用 Hbase。问题是HbaseTemplate
使用HConnection
and HTableInterface
。
我怎样才能让我的连接保持活跃HbaseTemplate
?启动新连接非常耗时,我只想做一次。或者还有其他方法可以从Spring
应用程序连接到 Hbase 吗?
我正在使用:
org.springframework.data:spring-data-hadoop:2.5.0.RELEASE
org.apache.hbase:hbase-client:1.1.2
解决方案
我找到了两个解决这个问题的方法:
HbaseAccessor
扩展和实现的自定义 HbaseTemplateHbaseOperations
最好的方法似乎是创建一个自定义类,它以与原始类类似的方式扩展HbaseAccessor
和实现,但使用更新的 API(即,而不是等)HbaseOperations
HbaseTemplate
Table
HTableInterface
在easyhbase项目中可以找到如何实现的示例之一。
注入Connection
代替HbaseTemplate
另一种解决方案是注入Connection
存储库并在那里完成所有繁重的工作:
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.stream.Collectors;
import java.stream.StreamSupport;
@Component
public class ItemRepositoryImpl implements ItemRepository {
@Autowired
private Connection connection;
@Override
public List<Item> findAll() throws IOException {
Scan scan = new Scan();
scan.addColumn(CF, CQ);
try (Table table = connection.getTable(TableName.valueOf(TABLE_NAME))) {
return StreamSupport
.stream(table.getScanner(scan).spliterator, false)
.map(...)
.collect(Collectors.toList());
}
}
}
@BeanConnection
可以这样配置:
@Configuration
public class HbaseConfiguration {
@Bean
public Connection() throws IOException {
org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
// configuration setup
return ConnectionFactory.createConnection(conf);
}
}
推荐阅读
- javascript - 在 React 路由器中动态路由路径问题
- android - 如何在 Kotlin 中扩展自定义视图?
- ngrok - Ngrok 隧道 https 通过配置
- c# - 如何在 Specflow 的同一功能文件中提供多个数据作为输入
- java - Java:如何获得匹配模式的下一次
- sql - SQL Server:子查询返回相同的值
- javascript - 如何从包含对象列表的文件中导出对象并将同一对象导入另一个文件以便能够使用它?
- sql - 计算与先前记录不同的时间
- javascript - 使用绘图板时会触发哪些 JS 事件?
- bash - 如何从 Linux 命令行检查二进制文件是否包含在另一个二进制文件中?