Spring HbaseTemplate使连接保持活动状态

时间:2020-05-28 14:58:36

标签: java spring hbase spring-data-hadoop

我设法使用HbaseSpring集成到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的连接(并在之后关闭)。我在某处读到,保持连接存活的方法是使用ConnectionTable来调用Hbase。问题是HbaseTemplate使用HConnectionHTableInterface

如何使用HbaseTemplate使连接保持活动状态?启动新连接非常耗时,我只想执行一次。另外,还有其他方法可以从Spring应用程序连接到Hbase吗?

我正在使用:

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

1 个答案:

答案 0 :(得分:0)

我找到了解决此问题的两种方法:

自定义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);
    }

}
相关问题