이 기사는 주로 Java FastDFS 클라이언트 사용 예제의 내용을 연구하며 특정 구현은 다음과 같습니다.
FastDF는 무엇입니까?
FASTDFS는 C 언어로 작성된 오픈 소스 분산 파일 시스템입니다. FASTDFS는 인터넷에 맞게 만들어졌으며 중복 백업,로드 밸런싱 및 선형 용량 확장과 같은 메커니즘을 완전히 고려하고 고 가용성 및 고성능과 같은 지표에주의를 기울입니다. FASTDF를 사용하여 파일 업로드, 다운로드 및 기타 서비스를 제공하기 위해 고성능 파일 서버 클러스터를 쉽게 구축 할 수 있습니다.
FASTDFS 아키텍처
FASTDFS 아키텍처에는 트래커 서버 및 스토리지 서버가 포함됩니다. 클라이언트는 트래커 서버에 파일을 업로드하고 다운로드하도록 요청하고 스토리지 서버는 최종적으로 트래커 서버 일정을 통해 파일을 업로드하고 다운로드합니다. 트래커 서버의 기능은로드 밸런싱 및 스케줄링입니다. 트래커 서버를 통해 파일을 업로드 할 때는 일부 전략에 따라 파일 업로드 서비스를 제공 할 수있는 스토리지 서버를 찾을 수 있습니다. 추적기를 추적 서버 또는 디스패치 서버라고 할 수 있습니다. 스토리지 서버의 목적은 파일 스토리지입니다. 클라이언트가 업로드 한 파일은 궁극적으로 스토리지 서버에 저장됩니다. Storage Server는 자체 파일 시스템을 구현하지 않지만 운영 체제의 파일 시스템을 사용하여 파일을 관리합니다. 스토리지를 스토리지 서버라고 할 수 있습니다.
예
1. Maven WebProject 호출을 만듭니다
파일 관리자 : mvnarchetype : create-dgroupid = platform.activity.fileManager-dartifactid = file-manager-darchetypeartifactid = maven-archetype-webapp
2. FASTDFS 클라이언트 파일 FDFS_CLIENT.CONF 정의 :
class = "properties"name = "code"> connect_timeout = 2network_timeout = 30 Charset = utf-8http.tracker_http_port = 8080http.anti_steal_token = nohttp.secret_key = fastdfs1234567890tracker =ser = 192.168.1.156:22122#Tracker_Server = 192.168.1.188:22122212221222212221222212222212222222222122222222222123000 여기서는 필요하지 않습니다
3. 구성 인터페이스 정의 :
패키지 com.chuanliu.platform.activity.fm.manager; import java.io.serializable; public interface filemanagerconfig 확장 {public static final string file_default_width = "120"; 공개 정적 최종 문자열 file_default_height = "120"; 공개 정적 최종 문자열 FILE_DEFAULT_AUTHOR = "DIANDI"; 공개 정적 최종 문자열 프로토콜 = "http : //"; 공개 정적 최종 문자열 분리기 = "/"; 공개 정적 최종 문자열 추적기 _ngnix_port = "8080"; 공개 정적 최종 문자열 client_config_file = "fdfs_client.conf"; }4. FastDFS 파일 Bean을 캡슐화하십시오
패키지 com.chuanliu.platform.activity.fm.manager; public class fastdfsfile 구현 filemanagerconfig {private static final long serialversionuid = -996760121932438618L; 개인 문자열 이름; 개인 바이트 [] 컨텐츠; 개인 문자열 내선; 개인 문자열 높이 = file_default_height; 비공개 문자열 너비 = file_default_width; 개인 문자열 author = file_default_author; public fastdfsfile (문자열 이름, 바이트 [] 컨텐츠, 문자열 내용, 문자열 높이, 문자열 너비, 문자열 작성자) {super (); this.name = 이름; this.content = 내용; this.ext = ext; this.height = 높이; this.width = 너비; this.author = 저자; } public fastdfsfile (문자열 이름, 바이트 [] 컨텐츠, 문자열 ext) {super (); this.name = 이름; this.content = 내용; this.ext = ext; } public byte [] getContent () {return 컨텐츠; } public void setContent (byte [] content) {this.content = content; } public String getext () {return ext; } public void setext (String Ext) {this.ext = ext; } public String getheight () {return height; } public void setheight (문자열 높이) {this.height = 높이; } public String getWidth () {리턴 너비; } public void setwidth (문자열 너비) {this.width = 너비; } public String getAuthor () {return awork. } public void setAuthor (문자열 저자) {this.author = 저자; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; }}5. 파일 업로드, 삭제 및 획득 방법이 포함 된 Core FilEmanager 클래스를 정의하십시오.
패키지 com.chuanliu.platform.activity.fm.manager; import java.io.file; import java.io.ioexception; import org.apache.log4j.logger; import org.csource.common.namevaluepair; import org.csource.fastdfs.clientglobal; import org.csource.fastdfs.fileinfo; import org.csource.fastdfs.serverinfo; import org.csource.astdfs.storageclient; import org.csource.astdfs.storageserver; import org.csource.astdfs.trackerclient; import org.cs.astdf; com.chuanliu.platform.activity.basic.util.loggerutils; public class filemanager는 filemanagerconfig {private static final long serialversionuid = 1l; private static logger = logger.getLogger (filemanager.class); 개인 정적 추적기 정적 추적기; StoragesErver; private static storageclient storageclient; static {// 빠른 DFS 클라이언트 구성 {string classPath = 새 파일 (fileManager.class.getResource ( "/"). getFile ()). getCanonicalPath (); String FDFSClientConfigFilePath = Classe.separator + + 파일 + + 파일. client_config_file; logger.info ( "빠른 DFS 구성 파일 경로 :" + fdfsclientConfigFilePath); clientGlobal.init (fdfsclientConfigFilePath); TrackerClient = new TrackerClient (); trackerSer = TrackerClient.GetConnection (); 새로운 StorageClient (); StoragesErver);} catch (예외 E) {loggerutils.error (logger, e);}} public static string upload (fastdfsfile file) {loggerutils.info (logger, "파일 이름 :" + file.getName () + " +" + 파일. namevaluepair [3]; meta_list [0] = new namevaluepair ( "width", "120"); meta_list [1] = new namevaluepair ( "heigth", "120"); meta_list [2] = new namevaluepair ( "author", "diandi"); uploadResults = null; try {uploadResults = storageClient.upload_file (file.getContent (), file.getext (), meta_list);} catch (ioException e) {logger.error ( "io 예외 파일 :" + file.gger (getname ()) " + file.getname (), e);} logger.info ("upload_file 시간 사용 : " + (System.CurrentTimeMillis () - startTime) +"ms "); if (uploadResults == null) {loggerUtils.error (logger,") = uploadResults [0]; String attremepilename = uploadResults [1]; String fileAbsolutePath = proceCole + TrackerserVer.GetInetSocketAddress (). gethostName () + 분리기 + tracker_ngnix_port + groupname + 분리기 + remoteFilename; loggerutils.info (upload file : " +" " +" " +" GroupName + ", ormetfileName :" + "" + ormoteFilename); return fileAbsolutePath;} public static fileInfo getFile (string groupName, String remoteFilename) {retud {return_file_info (groupname, remotefilename)} catch (ioexception e) { "ioexception e) dfs 실패 ", e);} catch (예외 e) {logger.error ("비 IO 예외 : 빠른 dfs 실패로부터 파일 가져옵니다 ", e);} return null;} public static void deletefile (String GroupName, String OrmiteFilename)은 예외 {storageclient.delete_file (groupname, remoteLename); getStorestorages (String GroupName)는 ioException {return trackerclient.getStorestorages (trackerserver, groupname);} public static serverInfo [] getFetchStorages (String groupName, String OrmetFilename)가 ioException {return TrackClient.getFetchStorages (grouperName, OrmetmerName, OrmeterName)를 던졌습니다.6. 단위 테스트 클래스
패키지 관리자; import java.io.file; import java.io.fileInputStream; import org.csource.fastdfs.fileinfo; import org.csource.fastdfs.serverinfo; import org.csource.storageservs.storageser; import org.junit.test; import org.junit.test; com.chuanliu.platform.activity.fm.manager.fastdfsfile; import com.chuanliu.platform.activity.fm.manager.fileManager;/** * @author Josh Wang (sheng) * * * @email [email protected] */public contation {) @Tovoid void (public void) 새 파일 ( "c : //520.jpg"); fileInputStream fis = new fileInputStream (content); byte [] file_buff = null; if (fis! = null) {int len = fis.available (); file_buff = new Byte [len]; fis.read (file_buff);} fastfile = new Fastdfs ( "520 file_buff, "jpg"); String fileabsolutepath = fileManager.upload (file); system.out.println (fileabsolutepath); fis.close ();}@test public void getfile () throws {fileInfo file = fileManager.getFile ( "Group1", "m00/00/00/wkgbm1n1-cianrlmaabygpyzdlw073.jpg"); assert.notnull (file); string sourceipaddr = file.getSourceipaddr (); long size = file.getFilesize (); system.out.out.out.porceipaddr (); getStoragesErver ()는 예외를 {StoragesErver [] ss = fileManager.getStorestorages ( "group1"); assert.notnull (ss); for (int k = 0; k <ss.length; k ++) {system.err.println (k + 1 + "." + ss [k] .getInetSocketAddress (). getAddress (). gethostAddress () + ":" + ss [k] .getInetSocketAddress (). getport ());}}@test public void getfetchstorages () 예외 {serverInfo [] servers = servers = filemanager.getfetchstorages ( "Group1", "m00/00/00/wkgbm1n1-cianrlmaabygpyzdlw073.jpg"); assert.notnull (서버); for (int k = 0; k <servers.length; k ++) {System.err.println (k + 1 + "." + serivers [k] .getipaddr () + " +" + " +" + " +" + " 서버 [k] .getport ());}}}
요약
위는 Java FastDFS 클라이언트의 인스턴스 코드 사용에 관한이 기사의 모든 내용이며, 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!