FastDFS简介
一、 概述
FastDFS是c语言编写的一款开源的分布式文件系统。FastDFS非常适合互联网,考虑了冗余备份、负载均衡、线性扩容等机制,并注重高可用、高性能等指标。使用FastDFS很容易搭建一套高性能的文件服务器集群提供文件上传、下载等服务。
FastDFS架构包括tracker server和storage server。客户端请求tracker server进行文件上传、下载,通过tracker server调度最终由storage server完成文件上传和下载。tracker server作用是负载均衡和调度,通过tracker server在文件上传时可以根据一些策略找到storage server提供文件上传服务。可以将tracker称为跟踪服务器或调度服务器。storage server作用是文件存储,客户端上传的文件最终存储在storage服务器上,storage server没有实现自己的文件系统而是利用操作系统的文件系统来管理文件。可以将storage称为存储服务器。
客户端上传文件后存储服务器将文件id返回给客户端,此文件id用于以后访问该文件的索引信息。文件索引信息包括,组名、虚拟磁盘路径、数据两级目录、文件名。
二、 搭建和使用简单的图片服务器
搭建一个单节点的图片服务器。
将FastDNSClient加入到本地仓库或者私服。在工程的表现层,引入FastNFSClient的依赖。
编写方法测试图片上传。
编写一个FastDNSClient的工具类。
publicclass FastDFSClient {
private TrackerClient trackerClient = null;
private TrackerServer trackerServer = null;
private StorageServer storageServer = null;
private StorageClient1 storageClient = null;
public FastDFSClient(String conf) throws Exception {
if (conf.contains("classpath:")) {
conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
}
ClientGlobal.init(conf);
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageServer = null;
storageClient = new StorageClient1(trackerServer, storageServer);
}
/**
* 上传文件方法
* <p>
* Title: uploadFile
* </p>
* <p>
* Description:
* </p>
*
* @param fileName
* 文件全路径
* @param extName
* 文件扩展名,不包含(.)
* @param metas
* 文件扩展信息
* @return
* @throws Exception
*/
public StringuploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
String result = storageClient.upload_file1(fileName, extName, metas);
returnresult;
}
public StringuploadFile(String fileName) throws Exception {
return uploadFile(fileName, null, null);
}
public StringuploadFile(String fileName, String extName) throws Exception {
return uploadFile(fileName, extName, null);
}
/**
* 上传文件方法
* <p>
* Title: uploadFile
* </p>
* <p>
* Description:
* </p>
*
* @param fileContent
* 文件的内容,字节数组
* @param extName
* 文件扩展名
* @param metas
* 文件扩展信息
* @return
* @throws Exception
*/
public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
String result = storageClient.upload_file1(fileContent, extName, metas);
returnresult;
}
public String uploadFile(byte[] fileContent) throws Exception {
return uploadFile(fileContent, null, null);
}
public String uploadFile(byte[] fileContent, String extName) throws Exception {
return uploadFile(fileContent, extName, null);
}
}
编写测试类
@Test
public void test2() throws Exception {
FastDFSClient fastDFSClient = newFastDFSClient("H:/xxx/xxx/xxx/client.conf");
String file = fastDFSClient.uploadFile("H:/vv/vv/1.jgp");
System.out.println(file);
}