关闭Mongo的自动化配置
因为项目需要配置MongoDB
多数据源.
为了避免Spring boot
自动化配置带来的影响,因此通过注解屏蔽MongoDB
的自动化配置
.
@SpringBootApplication(exclude =
{MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class StatApplication {
public static void main(String[] args) {
SpringApplication.run(StatApplication.class, args);
}
}
配置文件
个人倾向于使用uri
方式初始化MongoClient
,配置如下所示:
mongodb:
meta:
uri: mongodb://*:27017/admin?maxPoolSize=64
stat:
uri: mongodb://*:27017/stat?maxPoolSize=64
配置代码
@Data
@Configuration
public class MorphiaConfig {
@Value("${mongodb.meta.uri}")
private String metaUri;
@Value("${mongodb.stat.uri}")
private String statUri;
@Bean("metaMongoClient")
public MongoClient metaMongoClient() {
final MongoClientOptions.Builder builder = MongoClientOptions.builder()
.maxConnectionIdleTime(6000)
.maxConnectionLifeTime(0);
return new MongoClient(new MongoClientURI(metaUri, builder));
}
@Bean("statMongoClient")
public MongoClient statMongoClient() {
final MongoClientOptions.Builder builder = MongoClientOptions.builder()
.maxConnectionIdleTime(6000)
.maxConnectionLifeTime(0);
return new MongoClient(new MongoClientURI(statUri, builder));
}
@Bean("metaDataStore")
public Datastore metaDataStore(@Autowired @Qualifier("metaMongoClient") MongoClient mongoClient) {
Morphia res = new Morphia();
// 扫描实体类
res.mapPackage("com.*.*.entity.meta");
Datastore datastore = res.createDatastore(mongoClient, "metadata");
// 建立索引
datastore.ensureIndexes();
return datastore;
}
@Bean("statDataStore")
public Datastore statDataStore(@Autowired @Qualifier("statMongoClient") MongoClient mongoClient) {
Morphia res = new Morphia();
// 扫描实体类
res.mapPackage("com.*.*.entity.stat");
Datastore datastore = res.createDatastore(mongoClient, "stat");
// 建立索引
datastore.ensureIndexes();
return datastore;
}
}
通过以上代码,就可以建立两个独立的Datastore
对象,可以通过对应的Bean name
进行引入.
PS:
如果您觉得我的文章对您有帮助,可以扫码领取下红包或扫码支持(随意多少,一分钱都是爱),谢谢!
支付宝红包 | 支付宝 | 微信 |
---|---|---|
![]() | ![]() | ![]() |