引言:
上篇博客我演示了傳統的java方式操作fastdfs的步驟,請參考:fastdfs的入門到精通(java操作)
現在我們主流使用的是springboot,這篇我主要討論一下springboot與fastdfs的整合:注意,上節java操作時講到如果使用fastdfs客戶端的操作,最好自己根據公司情況自己打包然后使用,本節由於沒有特例化功能,我會采用官網jar進行演示(作者也在同步jar,然后我再下面演示中未發現問題)。下面我相關客戶端jar包引用地址:https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client
整合步驟:
第一步: 初始化一個springboot的項目,我還是在上節fastdfs父目錄下創建fastdfs_springboot項目:然后引入fastdfs的pom文件
第二步:配置文件
第三步:配置類設置:
第四步: 編輯測試類測試:
package com.huhy; import com.github.tobato.fastdfs.domain.fdfs.FileInfo; import com.github.tobato.fastdfs.domain.fdfs.MetaData; import com.github.tobato.fastdfs.domain.fdfs.StorePath; import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray; import com.github.tobato.fastdfs.service.FastFileStorageClient; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.*; import java.util.HashSet; import java.util.Set; @RunWith(SpringRunner.class) @SpringBootTest public class FastdfsSpringbootApplicationTests { @Autowired private FastFileStorageClient fastFileStorageClient; /** * StorePath [group=group1, path=M00/00/00/wKjsgl5wu0uAEmdBAAAABkeezIs297.txt] * @throws FileNotFoundException * 測試文件上傳api */ @Test public void contextLoads() throws FileNotFoundException { //上傳原文件 File file = new File("F:/huhy.txt"); FileInputStream fileInputStream = new FileInputStream(file); Set<MetaData> metaDataSet = new HashSet<>(); metaDataSet.add(new MetaData("author","huhy")); StorePath txt = fastFileStorageClient.uploadFile(fileInputStream, file.length(), "txt", metaDataSet); System.out.println(txt); } /** * 測試下載 * @throws IOException */ @Test public void testDownload() throws IOException { byte[] group1s = fastFileStorageClient.downloadFile("group1", "M00/00/00/wKjsgl5wu0uAEmdBAAAABkeezIs297.txt", new DownloadByteArray()); FileOutputStream fileOutputStream = new FileOutputStream("f:/huhy_copt.txt"); fileOutputStream.write(group1s); } /** * 獲取元數據信息 * metaDataSet.add(new MetaData("author","huhy")); * */ @Test public void testGetMeta(){ Set<MetaData> group1 = fastFileStorageClient.getMetadata("group1", "M00/00/00/wKjsgl5wu0uAEmdBAAAABkeezIs297.txt"); /** * 獲取的就是上傳文件是我們設置的metaDataSet.add(new MetaData("author","huhy"));相關屬性 * 上述設置可以是多個,因為是數組。演示我只設置了一個,僅供參考 */ for (MetaData metaData : group1) { System.out.println(metaData); } } /** * 獲取文件基礎屬性信息 * */ @Test public void testGetInfo(){ FileInfo fileInfo = fastFileStorageClient.queryFileInfo("group1", "M00/00/00/wKjsgl5wu0uAEmdBAAAABkeezIs297.txt"); /** * source_ip_addr = 192.168.236.130, 獲取相關tracker服務器的ip * file_size = 6, 文件大小 * create_timestamp = 2020-03-17 19:58:03, 時間戳 * crc32 = 1201589387 crc32 校驗 */ System.out.println(fileInfo); } }
到這,springboot的整合操作簡單完成,上面我只測試部分api,如有興趣,可以測試其他api
注意: 關於springboot操作api和上節java操作api有差異,底層調用方法原理沒變,建議有時間的可以看看源碼實現。