sprinboot之mongodb
一、MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
二、MongoDB常见使用场景用于处理文档的存放等,这样的目的主要是更加便于管理
三、MongoDB的安装:https://www.cnblogs.com/ll409546297/p/6474306.html
四、MongoDB的应用
1)目录
2)依赖包(pom.xml)
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.0.6.RELEASE</version> </dependency> </dependencies>
3)需要用到的下载配置MongoConfiguration
/** * file 文件处理配置 */ @Configuration public class MongoConfiguration { @Bean public GridFSBucket gridFSBucket(MongoDbFactory mongoDbFactory) { //主要是配置GridFSBuckets用于下载 return GridFSBuckets.create(mongoDbFactory.getDb()); } }
4)实现过程MongoServiceImpl
@Service @Transactional public class MongoServiceImpl implements IMongoService { @Autowired private GridFsTemplate gridFsTemplate; @Autowired private GridFSBucket gridFSBucket; @Autowired private MongoTemplate mongoTemplate; /** * 上传文件 * @param file * @return * @throws FileNotFoundException */ @Override public String uploadFile(File file) throws FileNotFoundException { ObjectId objectId = gridFsTemplate.store(new FileInputStream(file), file.getName()); return objectId.toHexString(); } /** * 上传文件 * @param inputStream * @param fileName * @return */ @Override public String uploadFile(InputStream inputStream, String fileName) { ObjectId objectId = gridFsTemplate.store(inputStream, fileName); return objectId.toHexString(); } /** * 下载文件 * @param mongoId * @param outputStream */ @Override public void downloadFile(String mongoId, OutputStream outputStream) throws IOException { // GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(mongoId))); // GridFsResource gridFsResource = new GridFsResource(gridFSFile); // IOUtils.copy(gridFsResource.getInputStream(), outputStream); //上面这种方式也可以实现下载 gridFSBucket.downloadToStream(new ObjectId(mongoId), outputStream); } /** * 删除文件 * @param mongoId */ @Override public void deleteFile(String mongoId) { gridFsTemplate.delete(Query.query(Criteria.where("_id").is(mongoId))); } /** * 保存对象 * @param t * @param <T> */ @Override public <T> void save(T t) { mongoTemplate.save(t); } /** * 查询对象 * @param query * @param clazz * @param <T> * @return */ @Override public <T> List<T> find(Query query, Class<T> clazz) { return mongoTemplate.find(query, clazz); } /** * 查询单个对象 * @param query * @param clazz * @param <T> * @return */ @Override public <T> T findOne(Query query, Class<T> clazz) { return mongoTemplate.findOne(query, clazz); } /** * 删除对象 * @param query * @param clazz * @param <T> */ @Override public <T> void delete(Query query, Class<T> clazz) { mongoTemplate.findAndRemove(query, clazz); } }
说明:这里包含了两个部分,一个是文件,一个是对象的处理
5)测试
a、文件测试FileController
@RestController @RequestMapping(value = "/file") public class FileController { private Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired private IMongoService mongoService; @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public ResultInfo uploadFile(MultipartFile multipartFile) { ResultInfo resultInfo = new ResultInfo(); try { resultInfo.setData(mongoService.uploadFile(multipartFile.getInputStream(), multipartFile.getOriginalFilename())); } catch (Exception e) { logger.error("upload file error:", e); resultInfo.setStatus(false); resultInfo.setFailCode(e.getMessage()); } return resultInfo; } @RequestMapping(value = "/downloadFile", method = RequestMethod.POST) public ResultInfo downloadFile(@RequestBody Map<String, Object> map, HttpServletResponse response) { ResultInfo resultInfo = new ResultInfo(); try { response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=test.mp3"); mongoService.downloadFile(map.get("mongoId").toString(), response.getOutputStream()); } catch (Exception e) { logger.error("download file error:", e); resultInfo.setStatus(false); resultInfo.setFailCode(e.getMessage()); } return resultInfo; } @RequestMapping(value = "/deleteFile", method = RequestMethod.POST) public ResultInfo deleteFile(@RequestBody Map<String, Object> map) { ResultInfo resultInfo = new ResultInfo(); try { mongoService.deleteFile(map.get("mongoId").toString()); } catch (Exception e) { logger.error("delete file error:", e); resultInfo.setStatus(false); resultInfo.setFailCode(e.getMessage()); } return resultInfo; } }
b、对象测试
/** * 对象存储,测试 */ @Component public class MongoTask implements CommandLineRunner { @Autowired private IMongoService mongoService; @Override public void run(String... args) throws Exception { mongoService.save(new User(1L, "test1", 25)); mongoService.save(new User(2L, "test2", 25)); System.out.println(mongoService.find(Query.query(Criteria.where("name").regex("test")), User.class)); System.out.println(mongoService.findOne(Query.query(Criteria.where("name").is("test2")), User.class)); mongoService.delete(Query.query(Criteria.where("name").is("test2")), User.class); } }
五、源码地址:https://github.com/lilin409546297/spring-mongodb