自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

基于Mongodb的分布式文件存儲(chǔ)實(shí)現(xiàn)

存儲(chǔ) 存儲(chǔ)架構(gòu)
基于 MongoDB GridFS 的分布式文件存儲(chǔ)方案,憑借其獨(dú)特的文件分塊存儲(chǔ)原理和與 MongoDB 分布式架構(gòu)的緊密結(jié)合,為我們提供了一種高效、可靠的文件存儲(chǔ)方式。

基于mongo GridFS實(shí)現(xiàn)文件上傳下載

分布式文件存儲(chǔ)的方案有很多,今天分享一個(gè)基于mongodb數(shù)據(jù)庫來實(shí)現(xiàn)文件的存儲(chǔ),mongodb支持分布式部署,以此來實(shí)現(xiàn)文件的分布式存儲(chǔ)。

基于 MongoDB GridFS 的分布式文件存儲(chǔ)實(shí)現(xiàn):從原理到實(shí)戰(zhàn)

一、引言

當(dāng)系統(tǒng)存在大量的圖片、視頻、文檔等文件需要存儲(chǔ)和管理時(shí),對(duì)于分布式系統(tǒng)而言,如何高效、可靠地存儲(chǔ)這些文件是一個(gè)關(guān)鍵問題。MongoDB 的 GridFS 作為一種分布式文件存儲(chǔ)機(jī)制,為我們提供了一個(gè)優(yōu)秀的解決方案。它基于 MongoDB 的分布式架構(gòu),能夠輕松應(yīng)對(duì)海量文件存儲(chǔ)的挑戰(zhàn),同時(shí)提供了便捷的文件操作接口。

二、GridFS 原理剖析

GridFS 是 MongoDB 中用于存儲(chǔ)大文件的一種規(guī)范。它將文件分割成多個(gè)較小的 chunks(默認(rèn)大小為 256KB),并將這些 chunks 存儲(chǔ)在 fs.chunks 集合中,而文件的元數(shù)據(jù)(如文件名、大小、創(chuàng)建時(shí)間、MIME 類型等)則存儲(chǔ)在 fs.files 集合中。這樣的設(shè)計(jì)不僅能夠突破 MongoDB 單個(gè)文檔大小的限制(默認(rèn) 16MB),還能利用 MongoDB 的分布式特性,實(shí)現(xiàn)文件的分布式存儲(chǔ)和高效讀取。

例如,當(dāng)我們上傳一個(gè) 1GB 的視頻文件時(shí),GridFS 會(huì)將其切分為約 4096 個(gè) 256KB 的 chunks,然后將這些 chunks 分散存儲(chǔ)在不同的 MongoDB 節(jié)點(diǎn)上,同時(shí)在 fs.files 集合中記錄文件的相關(guān)信息。

三、Spring Boot 集成 GridFS

在實(shí)際項(xiàng)目中,我們通常使用 Spring Boot 與 MongoDB 結(jié)合,下面是具體的集成步驟與代碼示例。

3.1 添加依賴

在 pom.xml 文件中添加 Spring Boot 與 MongoDB 相關(guān)依賴:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

3.2 配置 MongoDB 連接

在 application.properties 中配置 MongoDB 的連接信息:

spring.data.mongodb.uri=mongodb://localhost:27017/fs
spring.data.mongodb.database=fs

3.3 編寫服務(wù)類

使用 GridFsTemplate 和 GridFSBucket 來實(shí)現(xiàn)文件的上傳、下載、刪除等操作:

@Service
publicclass MongoFsStoreService implements FsStoreService {

    privatefinal GridFsTemplate gridFsTemplate;

    private GridFSBucket gridFSBucket;

    public MongoFsStoreService(GridFsTemplate gridFsTemplate) {
        this.gridFsTemplate = gridFsTemplate;
    }

    @Autowired(required = false)
    public void setGridFSBucket(GridFSBucket gridFSBucket) {
        this.gridFSBucket = gridFSBucket;
    }

    /**
     * 上傳文件
     * @param in
     * @param fileInfo
     * @return
     */
    @Override
    public FileInfo uploadFile(InputStream in, FileInfo fileInfo){
        ObjectId objectId = gridFsTemplate.store(in, fileInfo.getFileId(), fileInfo.getContentType(), fileInfo);
        fileInfo.setDataId(objectId.toString());
        return fileInfo;
    }

    /**
     *
     * @param in
     * @param fileName
     * @return
     */
    @Override
    public FileInfo uploadFile(InputStream in, String fileName) {
        FileInfo fileInfo = FileInfo.fromStream(in, fileName);
        return uploadFile(in, fileInfo);
    }

    /**
     *
     * @param fileId
     * @return
     */
    @Override
    public File downloadFile(String fileId){
        GridFsResource gridFsResource = download(fileId);
        if( gridFsResource != null ){
            GridFSFile gridFSFile = gridFsResource.getGridFSFile();
            FileInfo fileInfo = JsonHelper.convert(gridFSFile.getMetadata(), FileInfo.class);

            try(InputStream in = gridFsResource.getInputStream()) {
                return FileHelper.newFile( in, fileInfo.getFileId() ); //
            } catch (IOException e) {
                thrownew RuntimeException(e);
            }
        }
        returnnull;
    }

    /**
     * 查找文件
     * @param fileId
     * @return
     */
    public GridFsResource download(String fileId) {
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(GridFsCriteria.whereFilename().is(fileId)));
        if (gridFSFile == null) {
            returnnull;
        }

        if( gridFSBucket == null ){
            return gridFsTemplate.getResource(gridFSFile.getFilename());
        }
        GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        returnnew GridFsResource(gridFSFile, downloadStream);
    }

    /**
     * 刪除文件
     * @param fileId
     */
    @Override
    public void deleteFile(String fileId) {
        gridFsTemplate.delete(Query.query(GridFsCriteria.whereFilename().is(fileId)));
    }

}

3.4 創(chuàng)建控制器

提供 REST API 接口,方便外部調(diào)用:

@RestController
@RequestMapping("/mongo")
publicclass MongoFsStoreController {

    privatefinal MongoFsStoreService mongoFsStoreService;

    public MongoFsStoreController(MongoFsStoreService mongoFsStoreService) {
        this.mongoFsStoreService = mongoFsStoreService;
    }

    /**
     *
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public ResponseEntity<Result> uploadFile(@RequestParam("file") MultipartFile file){
        try(InputStream in = file.getInputStream()){
            FileInfo fileInfo = convertMultipartFile(file);
            return ResponseEntity.ok( Result.ok(mongoFsStoreService.uploadFile(in, fileInfo)) );
        }catch (Exception e){
            return ResponseEntity.ok( Result.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()) );
        }
    }

    private FileInfo convertMultipartFile(MultipartFile file){
        FileInfo fileInfo = new FileInfo();
        fileInfo.setType(FilenameUtils.getExtension(file.getOriginalFilename()));
        fileInfo.setFileId(UUID.randomUUID().toString() + "." + fileInfo.getType()); //
        fileInfo.setFileName(file.getOriginalFilename());
        fileInfo.setSize(file.getSize());
        fileInfo.setContentType(file.getContentType());
        fileInfo.setCreateTime(new Date());
        return fileInfo;
    }

    /**
     *
     * @param fileId
     * @param response
     */
    @RequestMapping("/download")
    public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response){
        File file = mongoFsStoreService.downloadFile(fileId);
        if( file != null ){
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
            try {
                FileUtils.copyFile(file, response.getOutputStream());
            } catch (IOException e) {
                thrownew RuntimeException(e);
            }
        }
    }

    @RequestMapping("/download/{fileId}")
    public ResponseEntity<InputStreamResource> download(@PathVariable("fileId") String fileId) throws IOException {
        GridFsResource resource = mongoFsStoreService.download(fileId);
        if( resource != null ){
            GridFSFile gridFSFile = resource.getGridFSFile();
            FileInfo fileInfo = JsonHelper.convert(gridFSFile.getMetadata(), FileInfo.class);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileInfo.getFileName() + "\"")
                    .contentLength(fileInfo.getSize())
//                    .contentType(MediaType.parseMediaType(fileInfo.getContentType()))
                    .body(new InputStreamResource(resource.getInputStream()));
        }
//        return ResponseEntity.noContent().build();
        return ResponseEntity.internalServerError().build();
    }

    /**
     *
     * @param fileId
     * @return
     */
    @RequestMapping("/delete")
    public ResponseEntity<String> deleteFile(@RequestParam("fileId") String fileId){
        mongoFsStoreService.deleteFile(fileId);
        return ResponseEntity.ok("刪除成功");
    }

四、實(shí)戰(zhàn)中的常見問題與解決方案

4.1 文件下載時(shí)的內(nèi)存管理

在下載文件時(shí),GridFSDownloadStream 提供了流式處理的能力,避免一次性將整個(gè)文件加載到內(nèi)存中。我們可以通過 GridFsResource 將流包裝后直接返回給客戶端,實(shí)現(xiàn)邊讀邊傳,從而節(jié)省內(nèi)存。例如:

// 正確:直接返回 InputStreamResource,邊讀邊傳
return ResponseEntity.ok()
       .body(new InputStreamResource(resource.getInputStream()));

而應(yīng)避免將整個(gè)文件讀取到字節(jié)數(shù)組中再返回,如以下錯(cuò)誤示例:

// 錯(cuò)誤:將整個(gè)文件加載到內(nèi)存再返回
byte[] content = resource.getInputStream().readAllBytes(); 
return ResponseEntity.ok()
       .body(content);

五、總結(jié)

基于 MongoDB GridFS 的分布式文件存儲(chǔ)方案,憑借其獨(dú)特的文件分塊存儲(chǔ)原理和與 MongoDB 分布式架構(gòu)的緊密結(jié)合,為我們提供了一種高效、可靠的文件存儲(chǔ)方式。通過 Spring Boot 的集成,我們能夠快速在項(xiàng)目中實(shí)現(xiàn)文件的上傳、下載、查詢和刪除等功能。在實(shí)際應(yīng)用過程中,我們需要關(guān)注內(nèi)存管理、數(shù)據(jù)類型轉(zhuǎn)換、時(shí)間類型處理等常見問題,并采用合適的解決方案。隨著技術(shù)的不斷發(fā)展,GridFS 也在持續(xù)優(yōu)化和完善,將為更多的分布式文件存儲(chǔ)場(chǎng)景提供強(qiáng)大的支持。

對(duì)于中小文件存儲(chǔ),GridFS 是一個(gè)簡(jiǎn)單高效的選擇;對(duì)于超大規(guī)模文件或需要極致性能的場(chǎng)景,可以考慮結(jié)合對(duì)象存儲(chǔ)(如 MinIO、S3)使用。

責(zé)任編輯:武曉燕 來源: Java技術(shù)指北
相關(guān)推薦

2010-09-09 08:42:28

MongoDB

2017-04-13 10:51:09

Consul分布式

2022-10-27 10:44:14

分布式Zookeeper

2017-10-17 08:33:31

存儲(chǔ)系統(tǒng)分布式

2017-07-18 09:51:36

文件存儲(chǔ)系統(tǒng)

2013-08-29 13:46:18

MongoDBSession.Net

2017-10-27 08:40:44

分布式存儲(chǔ)剪枝系統(tǒng)

2020-09-27 06:52:22

分布式存儲(chǔ)服務(wù)器

2023-01-06 09:19:12

Seata分布式事務(wù)

2009-06-19 14:23:41

RMIJava分布式計(jì)算

2017-05-11 14:05:25

Consul分布式信號(hào)量

2015-04-21 09:39:03

javajava分布式爬蟲

2017-10-24 11:28:23

Zookeeper分布式鎖架構(gòu)

2024-08-12 16:20:27

2015-05-12 13:03:54

開源分布式存儲(chǔ)HDFS

2018-02-22 08:42:04

分布式存儲(chǔ)安全

2022-11-06 19:28:02

分布式鎖etcd云原生

2021-10-22 05:42:38

分布式存儲(chǔ)三副本系統(tǒng)

2018-10-29 12:51:35

分布式存儲(chǔ)元數(shù)據(jù)

2015-07-02 13:26:35

分布式存儲(chǔ)云存儲(chǔ)云平臺(tái)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)