最简单易行的spring/spring boot 集成hadoop

项目中我们需要在spring中集成,提供注解和spring配置文件两种配置方式,本篇文章旨在介绍整个操作流程,由浅入深,希望能对你有所帮助,本文参考自spring官方文档(spring-hadoop部分)。错漏之处,多谢指正!

build.gradle文件(gradle配置项目依赖比maven方便很多 推荐使用)

group 'cn.com.time.hadoop'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.springframework.data:spring-data-hadoop:2.5.0.RELEASE'
}

hadoop配置之xml方式(使用spring提供的hadoop命名空间)

下面是hadoop.xml文件的配置


<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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd">

    
    
    
    
        
        
        
    
    
    
    <hdp:configuration>
        fs.defaultFS=${hd.fs}
        hadoop.tmp.dir=file://${java.io.tmpdir}
        hangar=${number:18}
    hdp:configuration>

    <context:property-placeholder location="classpath:hadoop.properties" />
beans>

hadoop.properties配置文件

hd.fs=hdfs://192.168.8.100
java.io.tmpdir=/tmp/hadoop
number=18

java代码

package cn.com.time.hadoop.spring;

import org.apache.hadoop.conf.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo1 {

    /**
     * 通过Spring的配置文件启动spring
     */
    public void t1(){
        ApplicationContext ac=new ClassPathXmlApplicationContext("spring.xml");
        Configuration configuration= (Configuration) ac.getBean("hadoopConfiguration");
    }

    public static void main(String[] args) {
        Demo1 d=new Demo1();
        d.t1();
    }

}

运行以上代码,可以得到hadoop的配置,通过hadoop的配置,使用hadoop提供的sdk操作hadoop进行hive、mapreduce、hbase操作,详细配置可以参考https://docs.spring.io/spring-hadoop/docs/2.6.0.BUILD-SNAPSHOT/reference/html/springandhadoop-config.html#using-the-spring-for-apache-hadoop-namespace 到这来xml配置方式完成了,是不是很简单。下面我们使用它来向hdfs存储和获取一个文件。

代码如下

在spring boot中往往需要我们使用注解配置

你可能感兴趣的:(hadoop)