`

fastdfs使用实战(Java实例篇)

 
阅读更多
一、创建一个maven的webproject,叫file-manager:mvnarchetype:create-DgroupId=platform.activity.filemanager-DartifactId=file-manager-DarchetypeArtifactId=maven-archetype-webapp
二、定义一个fastDFS的客户端文件fdfs_client.conf:
connect_timeout = 2
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = FastDFS1234567890

tracker_server = 192.168.1.156:22122
#tracker_server = 192.168.1.188:22122

#storage_server = 192.168.1.155:23000 #no need here

三、定义一个配置接口:
/**
 * 
 */
package com.chuanliu.platform.activity.fm.manager;

import java.io.Serializable;

/**
 * @author Josh Wang(Sheng)
 *
 * @email  josh_wang23@hotmail.com
 */
public interface FileManagerConfig extends Serializable {

	public static final String FILE_DEFAULT_WIDTH 	= "120";
	public static final String FILE_DEFAULT_HEIGHT 	= "120";
	public static final String FILE_DEFAULT_AUTHOR 	= "Diandi";
	
	public static final String PROTOCOL = "http://";
	public static final String SEPARATOR = "/";
	
	public static final String TRACKER_NGNIX_PORT 	= "8080";
	
	public static final String CLIENT_CONFIG_FILE   = "fdfs_client.conf";
	
	
}




四、封装一个FastDFS文件Bean
/**
 * 
 */
package com.chuanliu.platform.activity.fm.manager;


/**
 * @author Josh Wang(Sheng)
 *
 * @email  josh_wang23@hotmail.com
 */
public class FastDFSFile implements FileManagerConfig {

	private static final long serialVersionUID = -996760121932438618L;

	private String name;
	
	private byte[] content;
	
	private String ext;
	
	private String height = FILE_DEFAULT_HEIGHT;
	
	private String width = FILE_DEFAULT_WIDTH;
	
	private String author = FILE_DEFAULT_AUTHOR;
	
	public FastDFSFile(String name, byte[] content, String ext, String height,
			String width, String author) {
		super();
		this.name = name;
		this.content = content;
		this.ext = ext;
		this.height = height;
		this.width = width;
		this.author = author;
	}
	
	public FastDFSFile(String name, byte[] content, String ext) {
		super();
		this.name = name;
		this.content = content;
		this.ext = ext;
	}

	public byte[] getContent() {
		return content;
	}

	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(String height) {
		this.height = height;
	}

	public String getWidth() {
		return width;
	}

	public void setWidth(String width) {
		this.width = width;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}



五、定义核心的FileManager类,里面包含有上传、删除、获取文件的方法:
/**
 * 
 */
package 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.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

import com.chuanliu.platform.activity.basic.util.LoggerUtils;

/**
 * File Manager used to provide the services to upload / download / delete the files
 * from FastDFS.
 * 
 * <note>In this version, FileManager only support single tracker, will enhance this later...</note>
 * 
 * @author Josh Wang(Sheng)
 *
 * @email  josh_wang23@hotmail.com
 */
public class FileManager implements FileManagerConfig {
	
	private static final long serialVersionUID = 1L;

	private static Logger logger  = Logger.getLogger(FileManager.class);
	
	private static TrackerClient  trackerClient;
	private static TrackerServer  trackerServer;
	private static StorageServer  storageServer;
	private static StorageClient  storageClient;

	static { // Initialize Fast DFS Client configurations
		
		try {
			String classPath = new File(FileManager.class.getResource("/").getFile()).getCanonicalPath();
			
			String fdfsClientConfigFilePath = classPath + File.separator + CLIENT_CONFIG_FILE;
			
			logger.info("Fast DFS configuration file path:" + fdfsClientConfigFilePath);
			ClientGlobal.init(fdfsClientConfigFilePath);
			
			trackerClient = new TrackerClient();
			trackerServer = trackerClient.getConnection();
			
			storageClient = new StorageClient(trackerServer, storageServer);
			
		} catch (Exception e) {
			LoggerUtils.error(logger,  e);
			
		}
	}
	
	
	
	public static String upload(FastDFSFile file) {
		LoggerUtils.info(logger, "File Name: " + file.getName() + "		File Length: " + file.getContent().length);
		
		NameValuePair[] meta_list = new NameValuePair[3];
	    meta_list[0] = new NameValuePair("width", "120");
	    meta_list[1] = new NameValuePair("heigth", "120");
	    meta_list[2] = new NameValuePair("author", "Diandi");
		
	    long startTime = System.currentTimeMillis();
		String[] uploadResults = null;
		try {
			uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
		} catch (IOException e) {
			logger.error("IO Exception when uploadind the file: " + file.getName(), e);
		} catch (Exception e) {
			logger.error("Non IO Exception when uploadind the file: " + file.getName(), e);
		}
		logger.info("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms");
		
		if (uploadResults == null) {
			LoggerUtils.error(logger, "upload file fail, error code: " + storageClient.getErrorCode());
		}
		
		String groupName 		= uploadResults[0];
		String remoteFileName   = uploadResults[1];
		
		String fileAbsolutePath = PROTOCOL + trackerServer.getInetSocketAddress().getHostName() 
				+ SEPARATOR
				+ TRACKER_NGNIX_PORT
				+ SEPARATOR 
				+ groupName 
				+ SEPARATOR 
				+ remoteFileName;
		
		
		LoggerUtils.info(logger, "upload file successfully!!!  " +"group_name: " + groupName + ", remoteFileName:"
				+ " " + remoteFileName);
		
		return fileAbsolutePath;
		
	}
	
	public static FileInfo getFile(String groupName, String remoteFileName) {
		try {
			return storageClient.get_file_info(groupName, remoteFileName);
		} catch (IOException e) {
			logger.error("IO Exception: Get File from Fast DFS failed", e);
		} catch (Exception e) {
			logger.error("Non IO Exception: Get File from Fast DFS failed", e);
		}
		return null;
	}
	
	public static void deleteFile(String groupName, String remoteFileName) throws Exception {
		storageClient.delete_file(groupName, remoteFileName);
	}
	
	public static StorageServer[] getStoreStorages(String groupName) throws IOException {
		return trackerClient.getStoreStorages(trackerServer, groupName);
	}
	
	public static ServerInfo[] getFetchStorages(String groupName, String remoteFileName) throws IOException {
		return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
	}
}




六、Unit Test测试类
package manager;
/**
 * 
 */


import java.io.File;
import java.io.FileInputStream;

import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.ServerInfo;
import org.csource.fastdfs.StorageServer;
import org.junit.Test;
import org.springframework.util.Assert;

import com.chuanliu.platform.activity.fm.manager.FastDFSFile;
import com.chuanliu.platform.activity.fm.manager.FileManager;

/**
 * @author Josh Wang(Sheng)
 *
 * @email  josh_wang23@hotmail.com
 */
public class TestFileManager {

	@Test
	public void upload() throws Exception {
		File content = new File("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);
	    }
		
		FastDFSFile file = new FastDFSFile("520", file_buff, "jpg");
		
		String fileAbsolutePath = FileManager.upload(file);
		System.out.println(fileAbsolutePath);
		fis.close();
	}
	
	@Test
	public void getFile() throws Exception {
		FileInfo file = FileManager.getFile("group1", "M00/00/00/wKgBm1N1-CiANRLmAABygPyzdlw073.jpg");
		Assert.notNull(file);
		String sourceIpAddr = file.getSourceIpAddr();
	    long size = file.getFileSize();
	    System.out.println("ip:" + sourceIpAddr + ",size:" + size);
	}
	
	@Test
	public void getStorageServer() throws Exception {
		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() throws Exception {
		ServerInfo[] servers = FileManager.getFetchStorages("group1", "M00/00/00/wKgBm1N1-CiANRLmAABygPyzdlw073.jpg");
		Assert.notNull(servers);
		
		for (int k = 0; k < servers.length; k++) {
    		System.err.println(k + 1 + ". " + servers[k].getIpAddr() + ":" + servers[k].getPort());
    	}
	}
	
}


文章来自: 程序员俱乐部(www.cxyclub.cn) 详文参考:http://www.cxyclub.cn/n/44103/
分享到:
评论

相关推荐

    【FastDFS专题】fastdfs使用实战(Java实例篇)

    NULL 博文链接:https://josh-persistence.iteye.com/blog/2067574

    整合java实例 FastDFS

    **FastDFS概述** ...以上是关于"整合java实例 FastDFS"的主要内容,通过理解FastDFS的基本原理和Java客户端的使用方法,开发者可以有效地将FastDFS集成到Java项目中,实现高效、稳定的文件存储和访问功能。

    fastdfs-client-java-1.27.zip

    它提供了易于使用的API,使得Java程序员可以方便地在项目中集成FastDFS服务。 2. **fastdfs-client-java-1.27-SNAPSHOT.pom**:这是Maven项目的依赖配置文件,包含了该库的依赖关系和版本信息。如果项目使用Maven...

    fastdfs-client-java-1.29-SNAPSHOT.jar

    使用`fastdfs-client-java`时,首先需要在项目中引入`fastdfs-client-java-1.29-SNAPSHOT.jar`和`commons-io-2.4.jar`这两个依赖库,然后根据`fdfs_client.conf`配置客户端,并通过`FastDFSClient`类提供的API进行...

    通过java向fastdfs上传文件实例

    本文将详细讲解如何通过Java开发语言来实现向FastDFS系统的文件上传功能。 FastDFS是一个高性能、轻量级的分布式文件系统,它对文件进行管理,包括文件存储、文件同步、文件访问(文件上传、文件下载)等功能,解决...

    fastdfs-client-javajar1.27-SNAPSHOT.zip

    总的来说,FastDFS客户端Java版是Java开发者与FastDFS服务交互的重要工具,它的使用涉及到项目构建配置、网络通信以及文件操作等多个方面。在开发过程中,理解并正确配置这个客户端是确保项目能够正常运行的关键。

    Java操作FastDFS示例代码

    本示例代码将帮助开发者理解如何使用Java与FastDFS进行交互。 在Java中,我们通常会使用FastDFS的Java客户端来实现文件的上传和下载。首先,你需要在项目中引入FastDFS的Java客户端库。这可以通过Maven或Gradle的...

    fastdfs-client-java-1.27

    《FastDFS客户端Java库1.27版...总之,FastDFS客户端Java库1.27版为Java开发者提供了一个便捷、高效的与FastDFS服务器交互的工具,结合源码阅读,开发者可以更深入地理解和定制化使用,以满足多样化的文件存储需求。

    FastDFS文件服务器Java客户端.zip

    Java客户端在使用FastDFS时,首先需要连接到跟踪服务器,获取到文件应该存储或访问的存储服务器信息。这个过程通常包括以下步骤: 1. **连接跟踪服务器**:客户端通过Java客户端库建立与跟踪服务器的连接。 2. **...

    fastdfs-client-java-1.27-RELEASE

    fastdfs-client-java-1.27-RELEASE 版本 很实用 spring boot整合fastdfs

    fastDFS断点续传实例

    本实例使用maven作为项目管理工具,maven能够方便地管理和依赖库,简化项目的构建过程。开发者需要在`pom.xml`文件中配置FastDFS的客户端和服务端依赖,以便在本地构建和运行项目。 5. **"vvhcc-fastdfs"项目结构*...

    fastdfs-client-java1.26

    本文将详细介绍FastDFS-client-java 1.26版本的主要特性和使用方法。 一、FastDFS-client-java 1.26概述 FastDFS-client-java 1.26是该SDK的一个重要版本,发布于2017年4月17日。这个版本主要关注稳定性和性能优化...

    fastdfs-client-java-1.27-SNAPSHOT.zip

    FastDFS客户端Java版的使用步骤大致如下: 1. **配置文件**:在项目中配置FastDFS的连接参数,包括Tracker Server的地址、端口等信息。 2. **初始化连接**:启动程序时,初始化FastDFS客户端,建立与Tracker Server...

    Java操作FastDFS文件上传

    Java操作FastDFS文件上传是Java开发中常见的一项任务,下面我们将详细探讨如何使用`fastdfs-client-java`库实现这一功能。 首先,我们需要在项目中引入`fastdfs-client-java`依赖。通常,可以通过Maven或Gradle将该...

    fastdfs的java客户端代码实例

    在这个Java客户端代码实例中,我们将深入探讨如何在Java环境中与FastDFS进行交互。 1. **FastDFS概述** - FastDFS设计目标是高可用、高扩展性,它将文件存储和文件访问(文件上传、文件下载)的功能分离,使得...

    java操作FastDfs-api(代码实例加jar包)

    在标题"java操作FastDfs-api(代码实例加jar包)"中,提到了使用Java API来操作FastDFS,这通常包括文件的上传、下载、删除等基本操作。`fastdfs-client-java-1.25.jar`是这个Java客户端的jar包,开发者需要将其引入到...

    fastdfs-client-java-master.zip

    使用FastDFS客户端Java库时,开发者需要配置FastDFS服务器的地址和相关参数,然后可以通过API调用来执行以下操作: 1. 文件上传:将本地文件上传到FastDFS服务器,返回文件ID。 2. 文件下载:根据文件ID从FastDFS...

    FastDFS客户端 FastDFS java客户端

    FastDFS服务器是一个轻量级的文件存储服务,结合Nginx使用,实现集群高可用,但是他的java客户端不是特别好找。本java客户端依赖包,能够完美整合实现FastDFS服务器的连接,上传、下载和删除。 内部附有简单API使用...

Global site tag (gtag.js) - Google Analytics