LoginSignup
4
4

More than 5 years have passed since last update.

Spring for Apache HadoopのHbaseTemplateをGroovy DSLで設定する

Posted at

JavaでHBaseを操作したい時hbase-clientライブラリを直接利用してもよいのですが、Spring for Apache HadoopのHbaseTemplateクラスを利用するとコネクションやHTableの管理をよろしくやってくれるので便利です。
Spring for Apache Hadoopの公式ドキュメントに設定方法が記載されています。

// default HBase configuration
<hdp:hbase-configuration/>

// wire hbase configuration (using default name 'hbaseConfiguration') into the template 
<bean id="htemplate" class="org.springframework.data.hadoop.hbase.HbaseTemplate" p:configuration-ref="hbaseConfiguration"/>

これはSpringのXML設定ファイルの一部を抜粋したもので、実際には以下のようなXMLファイルになります。

spring-hbase.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:hdp="http://www.springframework.org/schema/hadoop"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd">

  <hdp:hbase-configuration/>
  <bean id="htemplate" class="org.springframework.data.hadoop.hbase.HbaseTemplate" p:configuration-ref="hbaseConfiguration"/>
</beans>

XMLだとやはり冗長になってしまいます。公式ドキュメントにはXMLでの設定方法しか書かれていないのですが、Groovy DSLによる設定を使えばより簡潔に書けます。

spring-hbase.groovy
import org.springframework.data.hadoop.hbase.HbaseTemplate

beans {
    xmlns([hdp:'http://www.springframework.org/schema/hadoop'])
    hdp.'hbase-configuration'()
    htemplate(HbaseTemplate, hbaseConfiguration) {
    }
}

hbase-configurationに何も指定しないとクラスパス上のhbase-site.xmlの設定を使用します。Springの設定ファイルでHBaseの設定値を記述することもできます。例えばZookeeperのホストを設定する場合は

spring-hbase.groovy
import org.springframework.data.hadoop.hbase.HbaseTemplate

beans {
    xmlns([hdp:'http://www.springframework.org/schema/hadoop'])
    hdp.'hbase-configuration'(
        'zk-quorum': 'host1,host2,host3'
    )
    htemplate(HbaseTemplate, hbaseConfiguration) {
    }
}

などとします。後はGenericGroovyApplicationContextで上記ファイルを読み込めばHbaseTemplateが使えます。

public static void main(String[] args) {
    ApplicationContext context = new GenericGroovyApplicationContext("classpath:/spring-hbase.groovy");
    HbaseTemplate template = context.getBean("htemplate", HbaseTemplate.class);
    ...
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4