MongoDB分布式存储GridFS

MongoDB分布式存储GridFS

项目结构图

在这里插入图片描述

配置文件

  1. pom.xml

    <!-- mongodb依赖包 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    
  2. application.yml

    server:
      port: 31001
    spring:
      application:
        name: xc‐service‐manage‐cms
      # MongoDB配置
      data:
        mongodb:
          uri: mongodb://root:123@localhost:27017
          database: xc_cms
      # freemarker模板配置
      freemarker:
        cache: false # 关闭模板缓存, 方便测试
        settings:
          template_update_delay: 0 # 立即刷新
      # rabbitmq配置
      rabbitmq:
        host: 127.0.0.1
        port: 5672
        username: guest
        password: guest
        virtual-host: /
    
    

配置类

  1. MongoConfig

    package com.xuecheng.manage_cms.config;
    
    import com.mongodb.MongoClient;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.gridfs.GridFSBucket;
    import com.mongodb.client.gridfs.GridFSBuckets;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @Author: 潇哥
     * @DateTime: 2020/11/2 下午5:25
     * @Description: GridFSBucket用于打开下载流对象
     */
    @Configuration
    public class MongoConfig {
    
        // 把application.yml中的配置信息赋值给db
        @Value("${spring.data.mongodb.database}")
        private String db;
    
        @Bean
        public GridFSBucket getGridFSBucket(MongoClient mongoClient) {
            // 获取数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase(db);
    
            // 获取打开下载流
            GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase);
           // 指定数据库下的集合
           // GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase, "集合名称");
            return gridFSBucket;
        }
    
    }
    

测试

  1. GridFsTest

    package com.xuecheng.manage_cms;
    
    import com.mongodb.client.gridfs.GridFSBucket;
    import com.mongodb.client.gridfs.GridFSDownloadStream;
    import com.mongodb.client.gridfs.model.GridFSFile;
    import org.apache.commons.io.IOUtils;
    import org.bson.types.ObjectId;
    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.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.gridfs.GridFsResource;
    import org.springframework.data.mongodb.gridfs.GridFsTemplate;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * @Author: 潇哥
     * @DateTime: 2020/10/18 下午2:43
     * @Description: TODO
     */
    @SpringBootTest // 它会扫描启动类下的所有包, 获取代理对象
    @RunWith(SpringRunner.class)
    public class GridFsTest {
    
    
        @Autowired
        private GridFsTemplate gridFsTemplate;
    
        @Autowired
        private GridFSBucket gridFSBucket;
    
    
        /**
         * 使用MongoDB分布式存储GridFs存文件
         */
        @Test
        public void testStore() throws FileNotFoundException {
            // 要存储的文件
            File file = new File("/Users/xiaoge/IdeaProjects/xcEduService/test-freemarker/src/main/resources/templates/index_banner.ftl");
    
            // 定义输入流
            FileInputStream fileInputStream = new FileInputStream(file);
    
            // 向GridFs存储文件
            ObjectId objectId = gridFsTemplate.store(fileInputStream, "index_banner.ftl");
            // 存储到制定的集合中
           // ObjectId objectId = gridFSBucket.uploadFromStream("index_banner.ftl", fileInputStream);
    
            // 得到文件id
            String fileId = objectId.toString();
    
            System.out.println(fileId);
    
        }
    
    
        /**
         * 使用MongoDB分布式存储GridFs读取文件
         */
        @Test
        public void testQuery() throws IOException {
    
            // 根据id查询文件
            GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5f9fcf8cbeed4e02ce629df8")));
    
            // 打开下载流对象
            GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
    
            // 创建gridFsResource,用于获取流对象
            GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
    
            // 获取文件内容
            String content = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");
    
            System.out.println(content);
    
        }
        
         /**
         * 根据文件id返回文件内容
         */
        @Test
         public String selectMedicalFileByObjectId(String objectId){
             ByteArrayOutputStream baos = new ByteArrayOutputStream();   
             gridFSBucket.downloadToStream(new ObjectId(objectId), baos);
             result =  baos.toString("UTF-8");
         }
    
        /**
         * 使用MongoDB分布式存储GridFs删除文件
         */
        @Test
        public void testDelete() {
            // 根据文件id删除fs.files和fs.chunks中的记录
            gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5f9fcf8cbeed4e02ce629df8")));
        }
    
    }
    
    

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只因为你温柔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值