SpringBoot 使用Mongo的GridFs實(shí)現(xiàn)分布式文件存儲(chǔ)操作
前言
這段時(shí)間在公司實(shí)習(xí),安排給我一個(gè)任務(wù),讓在系統(tǒng)里實(shí)現(xiàn)一個(gè)知識(shí)庫(kù)的模塊,產(chǎn)品說(shuō),就像百度網(wǎng)盤(pán)那樣。。。我tm…,這不就是應(yīng)了那句話,“這個(gè)需求很簡(jiǎn)單,怎么實(shí)現(xiàn)我不管”。
可是我google小能手怎么會(huì)認(rèn)輸呢,本來(lái)還說(shuō)研究一下FastDFS啥的,但是因?yàn)槲覀冺?xiàng)目用的Mongo作為數(shù)據(jù)庫(kù),了解到Mongo自帶分布式文件系統(tǒng)GridFs,這簡(jiǎn)直天助我也。
GridFs介紹
什么時(shí)候使用GridFs
我們平時(shí)使用Mongo也可以直接把文件的二進(jìn)制保存在Document中,就相當(dāng)于mysql的blob格式,但是mongo限制Document最大為16MB,那我們超過(guò)16MB的文件可咋辦吶,就可以利用GridFs來(lái)存儲(chǔ)。
- 在某些情況下,在MongoDB數(shù)據(jù)庫(kù)中存儲(chǔ)大文件可能比在系統(tǒng)級(jí)文件系統(tǒng)上更高效。
- 如果文件系統(tǒng)限制目錄中的文件數(shù),則可以使用GridFS根據(jù)需要存儲(chǔ)任意數(shù)量的文件。如果要從大型文件的各個(gè)部分訪問(wèn)信息而無(wú)需將整個(gè)文件加載到內(nèi)存中,可以使用GridFS調(diào)用文件的各個(gè)部分,而無(wú)需將整個(gè)文件讀入內(nèi)存。
- 如果要保持文件和元數(shù)據(jù)在多個(gè)系統(tǒng)和設(shè)施中自動(dòng)同步和部署,可以使用GridFS。使用地理位置分散的副本集時(shí),MongoDB可以自動(dòng)將文件及其元數(shù)據(jù)分發(fā)到多個(gè) mongod實(shí)例和工具中。
GridFs的原理
GridFS不是將文件存儲(chǔ)在單個(gè)文檔中,而是將文件分成多個(gè)部分或塊,并將每個(gè)塊存儲(chǔ)為單獨(dú)的文檔。
GridFS使用兩個(gè)集合來(lái)存儲(chǔ)文件。一個(gè)集合存儲(chǔ)文件塊,另一個(gè)存儲(chǔ)文件元數(shù)據(jù)。
默認(rèn)情況下,每一個(gè)塊的大小為255kB; 但最后一個(gè)塊除外。最后一個(gè)塊只有必要的大小。類似地,不大于塊大小的文件只有最終塊,只使用所需的空間和一些額外的元數(shù)據(jù)。
當(dāng)查詢GridFS文件時(shí),驅(qū)動(dòng)程序?qū)⒏鶕?jù)需要重新組裝塊??梢詫?duì)通過(guò)GridFS存儲(chǔ)的文件執(zhí)行范圍查詢。還可以從文件的任意部分訪問(wèn)信息,例如“跳過(guò)”到視頻或音頻文件的中間。
環(huán)境
- Spring Boot 2.0.4
- Maven 3.5
- Java 1.8
- MongoDB 4.0
- Robo 1.3.1
引入依賴和項(xiàng)目配置
首先添加Mongo客戶端的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
然后編寫(xiě)配置文件
spring: application: name: demo data: mongodb: uri: mongodb://root:你的密碼@localhost:27019 authentication-database: admin database: 你的數(shù)據(jù)庫(kù)
使用GridFsTemplate操作GridFs
GridFsTemplate是Spring提供的專門(mén)操作GridFs的客戶端,提供了一系列開(kāi)箱即用的方法
只要把它注入到我們的Conteoller中,就可以愉快的CRUD了,需要注意的是獲取文件時(shí)要注入MongoDbFactory ,我們使用默認(rèn)配置的話,直接注入就好。
import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import com.mongodb.client.gridfs.model.GridFSFile; import com.mongodb.client.gridfs.model.GridFSUploadOptions; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import org.bson.BsonValue; import org.bson.Document; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.*; @RestController @RequestMapping("/files") public class FileController { private Logger logger = LoggerFactory.getLogger(GridFsServiceImpl.class); //匹配文件ID的正則 private static Pattern NUMBER_PATTERN = Pattern.compile("(?<==).*(?=})"); @Autowired GridFsTemplate gridFsTemplate; @Autowired MongoDbFactory mongoDbFactory; /** * 上傳文件 * * @param file 文件 * @return 文件名和文件存儲(chǔ)的fileId鍵值對(duì)的Map */ @RequestMapping(value = "/upload", method = RequestMethod.POST) public Map<String, ObjectId> upload(@RequestParam(value = "file") MultipartFile file) { if(pathId == null || fileType == null || pathId.equals("") || fileType.equals("")){ logger.debug("上傳文件出錯(cuò)"); throw new RuntimeException("上傳文件出錯(cuò):pathId and fileType can not be null"); } Map<String, String> map = new HashMap<>(1); String fileName = file.getOriginalFilename(); //設(shè)置元數(shù)據(jù) DBObject metaData = new BasicDBObject(); metaData.put("userId","1"); metaData.put("fileExtension",FilenameUtils.getExtension(file.getOriginalFilename())); //存儲(chǔ)文件的擴(kuò)展名 try { InputStream inputStream = file.getInputStream(); ObjectId fileId = gridFsTemplate.store(inputStream, fileName,metaData); //這個(gè)getFileId是我自己封裝的獲取文件ID的方法 map.put(file.getOriginalFilename(),getFileId(fileId.toString())); } catch (IOException e) { logger.debug("上傳文件失敗: "+file); throw new RuntimeException("上傳文件失敗:"+e.getMessage()); } return map; } /** * 通過(guò)文件fileId下載文件 * * @param fileId 文件fileId * @param response 文件輸出流 */ @RequestMapping(value = "/downLoadByFileId") public void downLoadByFileId(@RequestParam(value = "fileId") ObjectId fileId, HttpServletResponse response) { GridFSFile gridFsFile = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("_id").is(fileId))); if (gridFsFile != null) { // mongo-java-driver3.x以上的版本就變成了這種方式獲取 GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb()); GridFSDownloadStream gridFsDownloadStream = bucket.openDownloadStream(gridFsFile.getObjectId()); GridFsResource gridFsResource = new GridFsResource(gridFsFile,gridFsDownloadStream); String fileName = gridFsFile.getFilename().replace(",", ""); //處理中文文件名亂碼 if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") || request.getHeader("User-Agent").toUpperCase().contains("TRIDENT") || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) { fileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } else { //非IE瀏覽器的處理: fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); } response.setHeader("Content-Disposition", "inline;filename=\"" + fileName + "\""); response.setContentType(application/octet-stream); IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream()); }else { logger.info("文件不存在"); } } /** * 根據(jù)文件名查詢文件列表 * @param fileName 文件名 * @return */ @RequestMapping("/search") public List<Map<String,Object>> search(String filePath, String fileName) { //這里返回的是一個(gè)List<Map<String,Object>> //因?yàn)镚ridFSFindIterable 迭代出來(lái)的GridFSFile不能直接返回 GridFSFindIterable gridFSFiles = gridFsTemplate.find(new Query().addCriteria (Criteria.where("filename").regex("^.*"+fileName+".*$"))); return getGridFSFiles(gridFSFiles); } /** * 通過(guò)fileId刪除文件 * @param fileId 文件ID * @return 成功為true, 失敗為false */ @RequestMapping("/deleteFilesByObjectId") public boolean deleteFilesByObjectId(@RequestParam(value = "fileId") String fileId) { try { gridFsTemplate.delete(new Query().addCriteria(Criteria.where("_id").is(fileId))); }catch (Exception e){ logger.debug("刪除文件失敗: fileId= "+fileId); throw new RuntimeException("刪除文件失?。?+e.getMessage()); } } /** * 根據(jù)GridFSFiles迭代器返回文件列表,因?yàn)椴荒苤苯臃祷?,所以?xiě)了這個(gè)工具方法 * @param gridFSFiles 從數(shù)據(jù)庫(kù)取出的文件集合 * @return List<Map<String,Object>> */ private List<Map<String,Object>> getGridFSFiles(GridFSFindIterable gridFSFiles){ List<Map<String,Object>> result = new ArrayList<>(); for (GridFSFile file : gridFSFiles) { HashMap<String,Object> map = new HashMap<>(6); map.put("fileId",getFileId(file.getId().toString())); map.put("fileName",file.getFilename()); map.put("fileExtension",file.getMetadata().get("fileExtension")); map.put("fileSize",file.getLength()/1024); map.put("uploadTime",file.getUploadDate()); map.put("user",file.getMetadata().get("userId")); result.add(map); } return result; } /** * 因?yàn)閺膍ongo中獲取的文件Id是BsonObjectId {value=5d7068bbcfaf962be4c7273f}的樣子 * 需要字符串截取 * @param bsonObjectId 數(shù)據(jù)庫(kù)文件的BsonObjectId */ private String getFileId(String bsonObjectId) { Matcher m = NUMBER_PATTERN.matcher(bsonObjectId); if(!m.find()){ return bsonObjectId; } return m.group(); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringBoot使用Minio進(jìn)行文件存儲(chǔ)的實(shí)現(xiàn)
- SpringBoot中整合Minio文件存儲(chǔ)的安裝部署過(guò)程
- Springboot集成minio實(shí)現(xiàn)文件存儲(chǔ)的實(shí)現(xiàn)代碼
- SpringBoot整合騰訊云COS對(duì)象存儲(chǔ)實(shí)現(xiàn)文件上傳的示例代碼
- springboot臨時(shí)文件存儲(chǔ)目錄配置方式
- SpringBoot整合阿里云OSS對(duì)象存儲(chǔ)服務(wù)實(shí)現(xiàn)文件上傳
- Spring File Storage文件的對(duì)象存儲(chǔ)框架基本使用小結(jié)
相關(guān)文章
一文詳解Java中的反射與new創(chuàng)建對(duì)象
Java中的反射(Reflection)和使用new關(guān)鍵字創(chuàng)建對(duì)象是兩種不同的對(duì)象創(chuàng)建方式,各有優(yōu)缺點(diǎn)和適用場(chǎng)景,本文小編給大家詳細(xì)介紹了Java中的反射與new創(chuàng)建對(duì)象,感興趣的小伙伴跟著小編一起來(lái)看看吧2024-07-07火遍全網(wǎng)的Hutool使用Builder模式創(chuàng)建線程池的方法
這篇文章主要介紹了火遍全網(wǎng)的Hutool使用Builder模式創(chuàng)建線程池的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03簡(jiǎn)單捋捋@RequestParam 和 @RequestBody的使用
這篇文章主要介紹了簡(jiǎn)單捋捋@RequestParam 和 @RequestBody的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Spring-AOP 靜態(tài)正則表達(dá)式方法如何匹配切面
這篇文章主要介紹了Spring-AOP 靜態(tài)正則表達(dá)式方法如何匹配切面的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07