首页 > 解决方案 > Spring HbaseTemplate 保持连接活跃

问题描述

我设法使用以下方法集成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(...)
        });
    }
}

但是,每次运行时都会打开与 Hbase 的连接findAll()(并在之后关闭)。我在某处读到保持连接活动的方法是使用ConnectionTable调用 Hbase。问题是HbaseTemplate使用HConnectionand HTableInterface

我怎样才能让我的连接保持活跃HbaseTemplate?启动新连接非常耗时,我只想做一次。或者还有其他方法可以从Spring应用程序连接到 Hbase 吗?

我正在使用:

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

标签: javaspringhbasespring-data-hadoop

解决方案


我找到了两个解决这个问题的方法:

HbaseAccessor扩展和实现的自定义 HbaseTemplateHbaseOperations

最好的方法似乎是创建一个自定义类,它以与原始类类似的方式扩展HbaseAccessor和实现,但使用更新的 API(即,而不是等)HbaseOperationsHbaseTemplateTableHTableInterface

在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);
    }

}

推荐阅读