1、建立连接mongodb
private MongoClient mongoClient;
/**通过传来的用户名称和密码为空来判断是否需要进行认证连接
* @param ip
* @param port
* @param database
* @return
*/
public MongoClient mongoConnection(String ip, int port, String database, String userName, String password) {
try {
if (StringUtil.isNotEmpty(ip) && StringUtil.isNotEmpty(database)) {
MongoClient mongoClient = null;
if (StringUtil.isNotEmpty(userName) && StringUtil.isNotEmpty(password)) {//开启验证
List adds = new ArrayList<>();
ServerAddress serverAddress = new ServerAddress(ip, port);
adds.add(serverAddress);
List credentials = new ArrayList<>();
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, database,
password.toCharArray());
credentials.add(mongoCredential);
mongoClient = new MongoClient(adds, credentials);
} else {//不开启验证
mongoClient = new MongoClient(ip, port);
}
return mongoClient;
} else {
return null;
}
} catch (Exception e) {
return null;
}}
【mongodb的使用和分桶】2、分桶上传文件到mongodb
try {
GridFSBucket bucket = null;
MongoDatabase db = mongoClient.getDatabase(数据库名称);
//这里是根据年度分桶的
if(fiscal != null){
String name = "test_" + fiscal;
//创建对应的文件桶
bucket = GridFSBuckets.create(db,name);
}else{
bucket = GridFSBuckets.create(db);
}
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
ObjectId fileId = bucket.uploadFromStream(附件名称, input);
//上传成功返回的标识fileId
return fileId.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
不分桶上传mongodb文件
try {
MongoDatabase db = mongoClient.getDatabase(数据库名称);
GridFSBucket bucket = GridFSBuckets.create(db);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
Object filed = bucket.uploadFromStream(附件名称, inputStream);
//返回的标识位objectId(fileId)
return filed.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
3、分桶读取mongodb上的文件(GridFSDownloadStream本身返回的是InputStream流)
GridFSDownloadStream gfStream = null;
try {
MongoDatabase db = mongoClient.getDatabase(数据库名称);
//根据年度分桶,如果年度为空去默认的桶里读取文件
if(fiscal != null){
String name = "test_" + fiscal;
GridFSBucket bucket = GridFSBuckets.create(db,name);
GridFSFindIterable fsFiles = bucket.find(Filters.eq("_id",new ObjectId(fileId)));
if(fsFiles.iterator().hasNext()){
//传来的标识位objectId(fileId)
gfStream = bucket.openDownloadStream(new ObjectId(fileId));
}else {
GridFSBucket buckets = GridFSBuckets.create(db);
gfStream = buckets.openDownloadStream(new ObjectId(fileId));
}
}else {
GridFSBucket bucket1 = GridFSBuckets.create(db);
gfStream = bucket1.openDownloadStream(new ObjectId(fileId));
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
//转换流
downloadToStream(gfStream, out);
//返回byte数组
return out.toByteArray();
} catch (Exception ex) {
return new byte[0];
} finally {
if (gfStream != null) {
try {
gfStream.close();
} catch (Exception e) {
}
}
}
//转换流
private void downloadToStream(final GridFSDownloadStream downloadStream, final OutputStream destination) {
byte[] buffer = new byte[downloadStream.getGridFSFile().getChunkSize()];
int len;
MongoGridFSException savedThrowable = null;
try {
while ((len = downloadStream.read(buffer)) != -1) {
destination.write(buffer, 0, len);
}
} catch (IOException e) {
savedThrowable = new MongoGridFSException("IOException when reading from the OutputStream", e);
} catch (Exception e) {
savedThrowable = new MongoGridFSException(
"Unexpected Exception when reading GridFS and writing to the Stream", e);
} finally {
if (savedThrowable != null) {
throw savedThrowable;
}
}
}
不分桶读取文件
GridFSDownloadStream gfStream = null;
try {
MongoDatabase db=mongoClient.getDatabase(数据库名称);
GridFSBucket bucket = GridFSBuckets.create(db);
//传来的标识位objectId
gfStream = bucket.openDownloadStream(new ObjectId(objectId));
ByteArrayOutputStream out = new ByteArrayOutputStream();
downloadToStream(gfStream, out);
if (out.size() == 0) {
return null;
}
return out.toByteArray();
} catch (Exception ex) {
return null;
} finally {
if (gfStream != null) {
try {
gfStream.close();
} catch (Exception e) {
LOG.error("关闭FS下载流报错:", e);
}
}
}
4、分桶删除文件
try {
MongoDatabase db = mongoClient.getDatabase(数据库名称);
if(fiscal != null){
String name = "test_" + fiscal;
GridFSBucket bucket = GridFSBuckets.create(db,name);
GridFSFindIterable fsFiles = bucket.find(Filters.eq("_id",new ObjectId(fileId)));
//传来的标识位objectId(fileId)
if(fsFiles.iterator().hasNext()){
bucket.delete(new ObjectId(fileId));
}else {
GridFSBucket buckets = GridFSBuckets.create(db);
buckets.delete(new ObjectId(fileId));
}
}else {
GridFSBucket bucket1 = GridFSBuckets.create(db);
bucket1.delete(new ObjectId(fileId));
}
} catch (Exception ex) {
log.error("delete file error:", ex);
}
不分桶删除文件
try {
MongoDatabase db = mongoClient.getDatabase(数据库名称);
GridFSBucket bucket = GridFSBuckets.create(db);
//根据传来的标识位objectId
bucket.delete(new ObjectId(objectId));
} catch (Exception e) {
e.printStackTrace()
return objectId;
}
推荐阅读
- 数据结构|模拟栈的实现(JAVA)
- MySQL|MySQL数据库:入门必备基础更新了哦~~~
- 【网络研讨会】MongoDB Vs 效仿者(选择MongoDB的理由)
- 《mongodb经典入门》|四.MongoDB入门-Java操作MongoDB
- 《mongodb经典入门》|五.MongoDB入门-SpringData操作MongoDB
- SpringBoot重点详解|SpringBoot重点详解--使用MongoDB
- 故障分析 | MongoDB 5.0 报错 Illegal instruction 解决
- MongoDB find getmore操作慢问题排查
- mongodb 6、mongodb内存使用优化