FastDFS的两个核心概念分别是:Tracker(跟踪器)、Storage(存储节点) 跟踪器Tracker主要做调度工作,相当于mvc中的controller的角色,在访问上起负载均衡的作用。跟踪器和存储节点都可以由一台或多台服务器构成,跟踪器和存储节点中的服务器均可以随时增加或下线而不会影响线上服务,其中跟踪器中的所有服务器都是对等的,可以根据服务器的压力情况随时增加或减少。跟踪器Tracker负责管理所有的Storage和group,每个Storage在启动后会连接Tracker,告知自己所属的group等信息,并保持周期性的心跳,tracker根据storage的心跳信息,建立group==>[storage server list]的映射表,Tracker需要管理的元信息很少,会全部存储在内存中;另外tracker上的元信息都是由storage汇报的信息生成的,本身不需要持久化任何数据,这样使得tracker非常容易扩展,直接增加tracker机器即可扩展为tracker cluster来服务,cluster里每个tracker之间是完全对等的,所有的tracker都接受stroage的心跳信息,生成元数据信息来提供读写服务。 存储节点Storage采用了分卷[Volume](或分组[group])的组织方式,存储系统由一个或多个组组成,组与组之间的文件是相互独立的,所有组的文件容量累加就是整个存储系统中的文件容量。 一个卷[Volume](组[group])可以由一台或多台存储服务器组成,一个组中的存储服务器中的文件都是相同的,组中的多台存储服务器起到了冗余备份和负载均衡的作用,数据互为备份,存储空间以group内容量最小的storage为准,所以建议group内的多个storage尽量配置相同,以免造成存储空间的浪费。

一、com.github.tobato.fastdfs-client

引入相关的依赖

  1. <dependency>
  2. <groupId>com.github.tobato</groupId>
  3. <artifactId>fastdfs-client</artifactId>
  4. <version>1.26.6</version>
  5. </dependency>

在application.yml当中配置Fdfs相关参数

  1. # ===================================================================
  2. # 分布式文件系统FDFS配置
  3. # ===================================================================
  4. fdfs:
  5. so-timeout: 1501
  6. connect-timeout: 601
  7. thumb-image: #缩略图生成参数
  8. width: 150
  9. height: 150
  10. webServerUrl: http://……/
  11. tracker-list: #TrackerList参数,支持多个
  12. - 192.168.1.105:22122
  13. - 192.168.1.106:22122

连接池配置,如果有必要可以参考 apache.pool2 参数配置连接池属性,默认配置为

  1. fdfs:
  2. ..其他配置信息..
  3. pool:
  4. #从池中借出的对象的最大数目(配置为-1表示不限制)
  5. max-total: -1
  6. #获取连接时的最大等待毫秒数(默认配置为5秒)
  7. max-wait-millis: 5*1000
  8. #每个key最大连接数
  9. max-total-per-key: 50
  10. #每个key对应的连接池最大空闲连接数
  11. max-idle-per-key: 10
  12. #每个key对应的连接池最小空闲连接数
  13. max_idle_per_key: 5

注意: key配置的是连接服务端的地址(IP+端口)连接情况,如果有连接不够用的情况可以调整以上参数

主要接口包括

  1. TrackerClient - TrackerServer接口
  2. GenerateStorageClient - 一般文件存储接口 (StorageServer接口)
  3. FastFileStorageClient - 为方便项目开发集成的简单接口(StorageServer接口)
  4. AppendFileStorageClient - 支持文件续传操作的接口 (StorageServer接口)

问题:

高并发下测试出现上传的文件和得到的返回路径的文件不是同一个

通过加大超时时间后解决

  1. soTimeout: 1500
  2. connectTimeout: 600

FastDFS客户端

  1. import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
  2. import com.github.tobato.fastdfs.domain.fdfs.StorePath;
  3. import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
  4. import com.github.tobato.fastdfs.service.FastFileStorageClient;
  5. import org.apache.commons.io.FilenameUtils;
  6. import org.apache.commons.lang3.StringUtils;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import java.io.ByteArrayInputStream;
  13. import java.io.File;
  14. import java.io.FileInputStream;
  15. import java.io.IOException;
  16. import java.nio.charset.Charset;
  17. @Component
  18. public class FastDFSClient {
  19. private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
  20. @Autowired
  21. private FastFileStorageClient storageClient;
  22. @Autowired
  23. private FdfsWebServer fdfsWebServer;
  24. /**
  25. * 上传文件
  26. * @param file 文件对象
  27. * @return 文件访问地址
  28. * @throws IOException
  29. */
  30. public String uploadFile(MultipartFile file) throws IOException {
  31. StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
  32. return getResAccessUrl(storePath);
  33. }
  34. /**
  35. * 上传文件
  36. * @param file 文件对象
  37. * @return 文件访问地址
  38. * @throws IOException
  39. */
  40. public String uploadFile(File file) throws IOException {
  41. FileInputStream inputStream = new FileInputStream (file);
  42. StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null);
  43. return getResAccessUrl(storePath);
  44. }
  45. /**
  46. * 将一段字符串生成一个文件上传
  47. * @param content 文件内容
  48. * @param fileExtension
  49. * @return
  50. */
  51. public String uploadFile(String content, String fileExtension) {
  52. byte[] buff = content.getBytes(Charset.forName("UTF-8"));
  53. ByteArrayInputStream stream = new ByteArrayInputStream(buff);
  54. StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
  55. return getResAccessUrl(storePath);
  56. }
  57. // 封装图片完整URL地址
  58. private String getResAccessUrl(StorePath storePath) {
  59. String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
  60. return fileUrl;
  61. }
  62. /**
  63. * 删除文件
  64. * @param fileUrl 文件访问地址
  65. * @return
  66. */
  67. public void deleteFile(String fileUrl) {
  68. if (StringUtils.isEmpty(fileUrl)) {
  69. return;
  70. }
  71. try {
  72. StorePath storePath = StorePath.parseFromUrl(fileUrl);
  73. storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
  74. } catch (FdfsUnsupportStorePathException e) {
  75. logger.warn(e.getMessage());
  76. }
  77. }
  78. }

二、org.csource.fastdfs-client-java

添加pom 依赖

  1. <dependency>
  2. <groupId>org.csource</groupId>
  3. <artifactId>fastdfs-client-java</artifactId>
  4. <version>1.27-SNAPSHOT</version>
  5. </dependency>

resources目录下添加fdfs_client.conf文件

  1. connect_timeout = 60
  2. network_timeout = 60
  3. charset = UTF-8
  4. http.tracker_http_port = 8080
  5. http.anti_steal_token = no
  6. http.secret_key = 123456
  7. tracker_server = 182.254.161.54:22122

上传工具类

  1. public class FastDFSClient {
  2. private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
  3. static {
  4. try {
  5. String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
  6. ClientGlobal.init(filePath);
  7. } catch (Exception e) {
  8. logger.error("FastDFS Client Init Fail!",e);
  9. }
  10. }
  11. public static String[] upload(FastDFSFile file) {
  12. logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
  13. NameValuePair[] meta_list = new NameValuePair[1];
  14. meta_list[0] = new NameValuePair("author", file.getAuthor());
  15. long startTime = System.currentTimeMillis();
  16. String[] uploadResults = null;
  17. StorageClient storageClient=null;
  18. try {
  19. storageClient = getTrackerClient();
  20. uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
  21. } catch (IOException e) {
  22. logger.error("IO Exception when uploadind the file:" + file.getName(), e);
  23. } catch (Exception e) {
  24. logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
  25. }
  26. logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
  27. if (uploadResults == null && storageClient!=null) {
  28. logger.error("upload file fail, error code:" + storageClient.getErrorCode());
  29. }
  30. String groupName = uploadResults[0];
  31. String remoteFileName = uploadResults[1];
  32. logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
  33. return uploadResults;
  34. }
  35. public static FileInfo getFile(String groupName, String remoteFileName) {
  36. try {
  37. StorageClient storageClient = getTrackerClient();
  38. return storageClient.get_file_info(groupName, remoteFileName);
  39. } catch (IOException e) {
  40. logger.error("IO Exception: Get File from Fast DFS failed", e);
  41. } catch (Exception e) {
  42. logger.error("Non IO Exception: Get File from Fast DFS failed", e);
  43. }
  44. return null;
  45. }
  46. public static InputStream downFile(String groupName, String remoteFileName) {
  47. try {
  48. StorageClient storageClient = getTrackerClient();
  49. byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
  50. InputStream ins = new ByteArrayInputStream(fileByte);
  51. return ins;
  52. } catch (IOException e) {
  53. logger.error("IO Exception: Get File from Fast DFS failed", e);
  54. } catch (Exception e) {
  55. logger.error("Non IO Exception: Get File from Fast DFS failed", e);
  56. }
  57. return null;
  58. }
  59. public static void deleteFile(String groupName, String remoteFileName)
  60. throws Exception {
  61. StorageClient storageClient = getTrackerClient();
  62. int i = storageClient.delete_file(groupName, remoteFileName);
  63. logger.info("delete file successfully!!!" + i);
  64. }
  65. public static StorageServer[] getStoreStorages(String groupName)
  66. throws IOException {
  67. TrackerClient trackerClient = new TrackerClient();
  68. TrackerServer trackerServer = trackerClient.getConnection();
  69. return trackerClient.getStoreStorages(trackerServer, groupName);
  70. }
  71. public static ServerInfo[] getFetchStorages(String groupName,
  72. String remoteFileName) throws IOException {
  73. TrackerClient trackerClient = new TrackerClient();
  74. TrackerServer trackerServer = trackerClient.getConnection();
  75. return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
  76. }
  77. public static String getTrackerUrl() throws IOException {
  78. return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ ClientGlobal.getG_tracker_http_port()+"/";
  79. }
  80. private static StorageClient getTrackerClient() throws IOException {
  81. TrackerServer trackerServer = getTrackerServer();
  82. StorageClient storageClient = new StorageClient(trackerServer, null);
  83. return storageClient;
  84. }
  85. private static TrackerServer getTrackerServer() throws IOException {
  86. TrackerClient trackerClient = new TrackerClient();
  87. TrackerServer trackerServer = trackerClient.getConnection();
  88. return trackerServer;
  89. }
  90. }

测试

  1. @PostMapping("/upload")
  2. public String singleFileUpload(@RequestParam("file") MultipartFile file,
  3. RedirectAttributes redirectAttributes) {
  4. if (file.isEmpty()) {
  5. redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
  6. return "redirect:uploadStatus";
  7. }
  8. try {
  9. // Get the file and save it somewhere
  10. String path=saveFile(file);
  11. redirectAttributes.addFlashAttribute("message",
  12. "You successfully uploaded '" + file.getOriginalFilename() + "'");
  13. redirectAttributes.addFlashAttribute("path",
  14. "file path url '" + path + "'");
  15. } catch (Exception e) {
  16. logger.error("upload file failed",e);
  17. }
  18. return "redirect:/uploadStatus";
  19. }
  20. @GetMapping("/uploadStatus")
  21. public String uploadStatus() {
  22. return "uploadStatus";
  23. }
  24. /**
  25. * @param multipartFile
  26. * @return
  27. * @throws IOException
  28. */
  29. public String saveFile(MultipartFile multipartFile) throws IOException {
  30. String[] fileAbsolutePath={};
  31. String fileName=multipartFile.getOriginalFilename();
  32. String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
  33. byte[] file_buff = null;
  34. InputStream inputStream=multipartFile.getInputStream();
  35. if(inputStream!=null){
  36. int len1 = inputStream.available();
  37. file_buff = new byte[len1];
  38. inputStream.read(file_buff);
  39. }
  40. inputStream.close();
  41. FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
  42. try {
  43. fileAbsolutePath = FastDFSClient.upload(file); //upload to fastdfs
  44. } catch (Exception e) {
  45. logger.error("upload file Exception!",e);
  46. }
  47. if (fileAbsolutePath==null) {
  48. logger.error("upload file failed,please upload again!");
  49. }
  50. String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
  51. return path;
  52. }
  53. }