spring hbasetemplate保持连接活动

yzckvree  于 2021-06-07  发布在  Hbase
关注(0)|答案(1)|浏览(528)

我成功地融入了 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 以及 HTableInterface .
我如何使用 HbaseTemplate ? 启动新连接非常耗时,我只想做一次。或者,是否有其他方法从服务器连接到hbase Spring 应用程序?
我正在使用:

org.springframework.data:spring-data-hadoop:2.5.0.RELEASE
org.apache.hbase:hbase-client:1.1.2
bxgwgixi

bxgwgixi1#

我找到了两种解决这个问题的方法:
自定义hbasetemplate,扩展 HbaseAccessor 和工具 HbaseOperations 最好的方法似乎是创建一个扩展 HbaseAccessor 和工具 HbaseOperations 以与原作相似的方式 HbaseTemplate 是的,但是使用更新的api(即。 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());
        }
    }
}

这个 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);
    }

}

相关问题