配置类里面主要建立。GridFSBucket这个对象。这个对象的做用就是用来打开一个下载流
在cms的微服务下,在config下建立MongoConfig。这个时候就须要用到spring的注解。@Configuration。加上这个注解。这个类就至关因而一个Bean。
用这个标识的类,spring的容器子在启动的时候。会扫描到这个Bean,而后就会把这个Bean注册到IOC容器中
这个类就是从配置文件中读取到mongo的database。
在建立GridFSBucket的时候须要指定是哪一个数据库
java
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; import org.springframework.data.mongodb.gridfs.GridFsTemplate; @Configuration public class MongoConfig { @Value("${spring.data.mongodb.database}") String db; @Bean public GridFSBucket getGridFsTemplate(MongoClient mongoClient){ MongoDatabase database = mongoClient.getDatabase(db); GridFSBucket bucket = GridFSBuckets.create(database); return bucket; } }
这是配置文件内配置的mongo的数据库信息
web
cms的微服务下,测试类GridFsTest内。注入GridFsBucket。目的是打开一个下载流
查询用到Criteria,Criteria就是一个条件对象。spring
把content复制出来。
mongodb
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; @SpringBootTest @RunWith(SpringRunner.class) public class GridFsTest { @Autowired GridFsTemplate gridFsTemplate; @Autowired GridFSBucket gridFSBucket; @Test public void testGridFsTemplate() throws FileNotFoundException { File file = new File("d:/index_banner.ftl"); FileInputStream fileInputStream = new FileInputStream(file); //定义fileInputSream ObjectId objectId = gridFsTemplate.store(fileInputStream, "index_banner.ftl"); System.out.println(objectId); } @Test public void queryFile() throws IOException { //根据文件id查询文件 GridFSFile gridFsFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5dbeb89bface36388cb8c7d4"))); //打开一个下载流对象 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); } }
自行测试
数据库