一、通过Docker 进行运行一个 mongodb实例
1、拉取镜像
java
docker pull mongo:5.0.5
2、创建 mongodb容器实例
java
docker run -d --name mongodb2 \
-e MONGO_INITDB_ROOT_USERNAME=salaryMongo \
-e MONGO_INITDB_ROOT_PASSWORD=123456 \
-p 27017:27017 \
mongo:5.0.5
3、进入容器,连接mongodb
java
#进入容器
docker exec -it mongodb2 bash
#查看数据库
test> show databases;
#切换admin数据库
test> use admin
#查询当前数据库的所有集合(表)
admin> db.getCollectionNames()
#查询当前库某个集合的记录
admin> db.admin.system.users.find()
4、客户端连接mongodb,这里以idea和navicat工具为例
下面是idea工具连接 mongodb示例图:
下面是 Navicat工具连接 mongodb示例图:
二、spring boot 连接 mongodb
1、这里用 spring boot 是2.2.2.RELEASE
java
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.52</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2、配置文件
java
mongodb:
db: salaryReport
host: localhost
port: 27017
username: salaryMongo
password: 123456
authDb: admin
3、配置类
java
@Data
@Component
@ConfigurationProperties(prefix = "mongodb")
public class MongoProperties {
/**
* 主机名
*/
private String host;
/**
* 端口
*/
private int port;
/**
* 集合
*/
private String db;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 认证数据库
*/
private String authDb;
}
java
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
/**
* 自定义Mingodb 配置
*/
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoConfig.class);
/**
* 配置文件
*/
@Autowired
private MongoProperties mongoProperties;
/**
* 自定义GridFsTemplate
*/
@Bean
public GridFsTemplate gridFsTemplate() {
return new GridFsTemplate(mongoTemplate().getMongoDbFactory(), mongoTemplate().getConverter(),this.getDatabaseName());
}
/**
* 自定义模板
*/
@Bean
public MongoTemplate mongoTemplate(){
SimpleMongoClientDbFactory factory = new SimpleMongoClientDbFactory(mongoClient(),this.getDatabaseName());
MongoTemplate mongoTemplate = new MongoTemplate(factory);
return mongoTemplate;
}
/**
* 自定义数据库名称
*/
@Override
@Bean
protected String getDatabaseName() {
return mongoProperties.getDb();
}
/**
* 自定义客户端
*/
@Override
@Bean
public MongoClient mongoClient() {
LOGGER.info("MongoDB Connection Details: Host: {}, Port: {}, Database: {}, Auth Database: {}, Username: {}",
mongoProperties.getHost(), mongoProperties.getPort(), getDatabaseName(),
mongoProperties.getAuthDb(), mongoProperties.getUsername());
//mongodb://salaryMongo:123456@localhost:27017/salaryReport?authSource=admin&retryWrites=true&w=majority
// Docker环境的MongoDB连接
String uri = String.format("mongodb://%s:%s@%s:%d/%s?authSource=admin&retryWrites=true&w=majority",
mongoProperties.getUsername(),
mongoProperties.getPassword(),
mongoProperties.getHost(),
mongoProperties.getPort(),
getDatabaseName());
LOGGER.info("MongoDB Connection URI: {}", uri);
return MongoClients.create(uri);
}
}
4、存储和读取文件接口
java
import com.bilibili.config.MongoProperties;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.gridfs.model.GridFSFile;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
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.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
@RestController
@RequestMapping(value = {"/api/exportFile"})
public class ExportFileController {
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private MongoProperties mongoProperties;
@ApiOperation(value = "上传Word文件")
@PostMapping(value = {"/uploadFile"})
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
//文件输入流
InputStream inputStream = file.getInputStream();
//文件名
String originalFilename = file.getOriginalFilename();
// 上传文件中我们也可以使用DBObject附加一些属性
DBObject metadata = new BasicDBObject();
//把文件存储到mongodb里
ObjectId objectId = gridFsTemplate.store(inputStream, originalFilename, mongoProperties.getDb(), metadata);
String result = objectId.toString();
// 处理文件流
inputStream.close();
System.out.println(result);
return ResponseEntity.ok(result);
}
/**
* 根据文件ID下载文件
* @param response
* @param param
* @return
* @throws IOException
*/
@PostMapping(value = {"/downloadFile"})
public ResponseEntity<Void> downloadFile(HttpServletResponse response, @RequestBody Map<String,String> param) throws IOException {
GridFsResource resource = null;
try {
String id = param.get("id");
// 根据文件ID从GridFS中获取文件
GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
if (file == null) {
throw new RuntimeException("文件不存在");
}
String contentType = file.getMetadata().getString("contentType");
response.setContentType(contentType);
// 从GridFS中获取文件流并写入响应输出流
resource = gridFsTemplate.getResource(file);
} catch (RuntimeException e) {
throw new RuntimeException(e);
}
InputStream fis = resource.getInputStream();
XWPFDocument document = new XWPFDocument(fis);
// 将修改后的文档内容写回文件
ServletOutputStream outputStream = response.getOutputStream();
document.write(outputStream);
// 关闭流
outputStream.close();
fis.close();
document.close();
return ResponseEntity.ok().build();
}
}
GridFS
在 MongoDB中,使用 GridFS存储大于 16MB 的文件。
GridFS 集合
GridFS 将文件存储在两个集合中:
chunks 存储着二进制数据块。有关详细信息,请参阅 chunks 集合。
files 存储文件的元数据。有关详细信息,请参阅 files 集合。
GridFS 通过为每个集合添加一个存储桶名称前缀,从而将这些集合放置在一个通用存储桶中。默认情况下,GridFS 使用两个集合以及带名为 fs 的存储桶:fs.files、fs.chunks
用于自管理部署的GridFS - MongoDB 手册 v8.0