Spring整合HDFS

Spring整合HDFS

1.實例環境 

在工作中 遇到了 HDFS在項目中的使用 但是 又不想去寫 這種 工具類 考慮種種 於是 讓Spring去託管 首先百度了 一下有沒有直接可以用的Demo結果發現並沒有

於是看了看 Java的HDFS操作

分析了 發現 開發中只需要得到FileSystem實例對象即可滿足需求

 

2.過程 首先需要加入Spring的包 Hadoop包 

首先我採用了 Spring的原始的Bean去注入,但是發現使用Set注入和構造注入並不能滿足我的需求 之後就採用了工廠方法注入

spring.xml

 	<bean id="configuratione" class="org.apache.hadoop.conf.Configuration" >
	</bean>
	<bean class="org.apache.hadoop.fs.FileSystem" id="fileSystem"  factory-method="get">
		<constructor-arg name="uri" value="hdfs://hadoop:9000"/> 
		<constructor-arg name="conf" ref="configuratione"/> 
		<constructor-arg name="user" value="root"/>
	</bean>  

這裏 強調的地方:配置了 factory-method 裏面調用了org.apache.hadoop.fs.FileSystem 類 的方法:

這樣  org.apache.hadoop.fs.FileSystem這個類就被 Spring給管理了起來 就可以實現我們的功能了

   

 後來 同事分享給我一個更方便的配置方法:

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

	<!-- 配置Configuration -->
	<hadoop:configuration></hadoop:configuration>
	<!-- 配置FileSystem -->
	<hadoop:file-system uri="hdfs://192.168.174.88:9000" user="root" id="fileSystem" />
	
 	<!-- 	原始Bean的注入方式
 	<bean id="configuratione" class="org.apache.hadoop.conf.Configuration"></bean>
	<bean class="org.apache.hadoop.fs.FileSystem" id="fileSystem"  factory-method="get">
		<constructor-arg name="uri" value="hdfs://hadoop:9000"/> 
		<constructor-arg name="conf" ref="configuratione"/> 
		<constructor-arg name="user" value="root"/>
	</bean>   -->

</beans>

這樣呢  使用了 hadop 標籤 免去了我們麻煩的配置 以上兩種就是 兩種 Spring整合HDFS的過程


寫了一個Demo測試類 


這樣就實現了 一個上傳!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章