我成功地使用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(...)
});
}
}但是,每次我运行findAll()时都会打开到Hbase的连接(然后就关闭)。我在某个地方读到,保持连接活动的方法是使用Connection和Table来调用Hbase。问题是HbaseTemplate使用了HConnection和HTableInterface。
如何使用HbaseTemplate保持连接正常?启动一个新的连接非常耗时,我只想做一次。或者,还有其他方式从Spring应用程序连接到Hbase吗?
我在用:
org.springframework.data:spring-data-hadoop:2.5.0.RELEASE
org.apache.hbase:hbase-client:1.1.2发布于 2020-05-29 14:53:49
我找到了两种解决这个问题的方法:
扩展HbaseAccessor 并实现 HbaseOperations的自定义HbaseTemplate
最好的方法似乎是创建一个自定义类,它扩展HbaseAccessor并以与原始HbaseTemplate类似的方式实现HbaseOperations,但使用较新的HbaseTemplate(即。( Table而不是HTableInterface等)
如何实现它的例子之一可以在平易近项目中找到。
注射而不是 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());
}
}
}Connection @Bean可以这样配置:
@Configuration
public class HbaseConfiguration {
@Bean
public Connection() throws IOException {
org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
// configuration setup
return ConnectionFactory.createConnection(conf);
}
}https://stackoverflow.com/questions/62067869
复制相似问题