技术背景:
jdk: 1.8
springboot: 2.7.6
mongodb: 4.4
一.创建默认的bucket: fs
(bucketName: fs), gridFsTemplate(bucketName: fs)
1.1:配置文件
spring:
servlet:
multipart:
max-file-size: 200MB #单个文件上传大小
max-request-size: 400MB #连续上传文件大小
#mongo配置-单机
data:
mongodb:
host: 127.0.0.1
port: 27017
database: test
username: root
password: "123456" #纯数字密码需要带双引号,否则报错
authentication-database: admin
1.2: mongoConfig类
如果不创建该bean, 在调用gridFSBucket时候会注入不成功
import com.mongodb.client.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 javax.annotation.Resource;
@Configuration
public class MongoConfig {
@Value("${spring.data.mongodb.database}")
private String db;
@Resource
private MongoClient mongoClient;
/**
* 创建默认的bucket, bucket name: fs
*/
@Bean
public GridFSBucket getGridFSBucket() {
MongoDatabase database = mongoClient.getDatabase(db);
return GridFSBuckets.create(database);
}
}
二.创建自定义的bucket
2.1: 配置文件
spring:
servlet:
multipart:
max-file-size: 100MB #单个文件上传大小
max-request-size: 200MB #连续上传文件大小
#mongo配置-单机
data:
mongodb:
host: 127.0.0.1
port: 27017
database: test
username: root
password: "123456" #纯数字密码需要带双引号,否则报错
authentication-database: admin
gridfs:
bucket: mms_fs #配置该属性就会创建同名的gridfs bucket: mms_fs. 不配置创建默认的bucket: fs
2.2:MongoConfig
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.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import javax.annotation.Resource;
@Configuration
public class MongoConfig {
@Value("${spring.da