1. 程式人生 > >FastDFS與Springboot整合

FastDFS與Springboot整合

上一篇《FastDFS分佈檔案系統Java客戶端使用》基於官方提供的Java客戶端庫介紹了檔案上傳、下載和刪除的功能。淘寶在今年9月份在官方Java客戶端的基礎上進行了大量重構,且提供了更多豐富的api,主要新增的特性如下:  1> 對關鍵部分程式碼加入了單元測試,便於理解與服務端的介面交易,提高介面質量  2> 將以前對byte硬解析風格重構為使用 物件+註解 的形式,儘量增強了程式碼的可讀性  3> 支援對服務端的連線池管理(commons-pool2)  4> 支援上傳圖片時候檢查圖片格式,並且自動生成縮圖  5> 和Springboot整合方便

整合到Springboot專案流程

注意:必須是Springboot專案

1、新增pom依賴

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

2、將Fdfs配置引入專案

我將註解配置加在springboot的入口類中:@Import(FdfsClientConfig.class)

@Import(FdfsClientConfig.class)
@SpringBootApplication
public class JingtongApplication {

    public static void main(String[] args) {
        SpringApplication.run(JingtongApplication.class, args);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3、在spring配置檔案中加入fdfs相關配置

根據專案當中使用配置檔案型別(.yml和.properties選擇其中一個),加入相應的配置。

application.yml

fdfs:
  soTimeout: 1500
  connectTimeout: 600
  thumbImage:             #縮圖生成引數
    width: 150
    height: 150
  trackerList:            #TrackerList引數,支援多個
    - 192.168.0.201:22122
    - 192.168.0.202:22122 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

application.properties

fdfs.soTimeout=1500
fdfs.connectTimeout=600
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
fdfs.trackerList[0]=192.168.0.201:22122
fdfs.trackerList[1]=192.168.0.202:22122
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4、在專案中使用

客戶端主要包括以下介面:  TrackerClient - TrackerServer介面  GenerateStorageClient - 一般檔案儲存介面 (StorageServer介面)  FastFileStorageClient - 為方便專案開發整合的簡單介面(StorageServer介面)  AppendFileStorageClient - 支援檔案續傳操作的介面 (StorageServer介面)

筆者在前一個專案當中將fdfs主要用於圖片儲存,基於FastFileStorageClient介面和springmvc提供的MultipartFile介面封裝了一個簡單的工具類,方便全域性管理與呼叫。如下所示:

package com.digi_zones.support.fs;

import com.digi_zones.config.AppConfig;
import com.digi_zones.contacts.AppConstants;
import com.github.tobato.fastdfs.domain.FileInfo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * <p>Description: FastDFS檔案上傳下載包裝類</p>
 * <p>Copyright: Copyright (c) 2016</p>
 *
 * @author 楊信
 * @version 1.0
 * @date 2016/9/7
 */
@Component
public class FastDFSClientWrapper {

    private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private AppConfig appConfig;   // 專案引數配置

    /**
     * 上傳檔案
     * @param file 檔案物件
     * @return 檔案訪問地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        return getResAccessUrl(storePath);
    }

    /**
     * 將一段字串生成一個檔案上傳
     * @param content 檔案內容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
        return getResAccessUrl(storePath);
    }

    // 封裝圖片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = AppConstants.HTTP_PRODOCOL + appConfig.getResHost()
                + ":" + appConfig.getFdfsStoragePort() + "/" + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 刪除檔案
     * @param fileUrl 檔案訪問地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.warn(e.getMessage());
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87

除了FastDFSClientWrapper類中用到的api,客戶端提供的api還有很多,可根據自身的業務需求,將其它介面也新增到工具類中即可。如下所示:

// 上傳檔案,並新增檔案元資料
StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 獲取檔案元資料
Set<MateData> getMetadata(String groupName, String path);
// 上傳圖片並同時生成一個縮圖
StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName,
            Set<MateData> metaDataSet);
// 。。。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在專案中使用FastDFSClientWrapper:

@Controller
public class MyController {

    @Autowired
    private FastDFSClientWrapper dfsClient;

    // 上傳圖片
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 省略業務邏輯程式碼。。。
        String imgUrl = dfsClient.uploadFile(file);
        // 。。。。
        return xxxx;

    }
}