spring data mongodb 代码连接数据库方式

时间:2022-05-06
本文章向大家介绍spring data mongodb 代码连接数据库方式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

平时我们用spring data mongodb都是采用xml配置的方式来链接数据库

但是往往有的时候需要用代码的方式来实现。

比如说我们有可能要同时操作多个db的数据,总不能一个db配置一个DbFactory吧。

这个时候就需要代码来动态创建和获取了。

下面贴上实现的代码,里面的参数都写死了,大家在做封装的时候可以作为参数传进去获取配置文件也行。

@Configuration
public class AppConfig { 
public @Bean MongoDbFactory mongoDbFactory() throws Exception {
 //mongodb地址,集群环境填多个
 List<ServerAddress> seeds = Arrays.asList(new ServerAddress("localhost", 27017));

//用户认证信息,参数为用户,数据库,密码
//MongoCredential com.mongodb.MongoCredential.createCredential(String userName, String database, char[] password)
    
MongoCredential mongoCredential = MongoCredential.createCredential("cxytiandi", "cxytiandi", "cxytiandi".toCharArray());
        
List<MongoCredential> credentialsList = Arrays.asList(mongoCredential);

//连接池参数配置
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        
// 每个主机的连接数
int connPerHost = 20;
builder.connectionsPerHost(connPerHost);
        
// 线程队列数
int threadCount = 20;
builder.threadsAllowedToBlockForConnectionMultiplier(threadCount);
        
// 最大等待连接的线程阻塞时间(单位:毫秒)
int maxWaitTime = 1000;
builder.maxWaitTime(maxWaitTime);
        
// 连接超时的时间。0是默认和无限(单位:毫秒)
int timeOut = 1000;
builder.connectTimeout(timeOut);

MongoClientOptions options = builder.build();

MongoClient mongoClient = new MongoClient(seeds, credentialsList, options);
//这里第二个参数也就是cxytiandi是用户认证的库名,在哪个库认证就表示登陆哪个库
return new SimpleMongoDbFactory(mongoClient, "cxytiandi");
}

public @Bean MongoTemplate mongoTemplate() throws Exception {
  return new MongoTemplate(mongoDbFactory());
}
public static void main(String[] args) throws Exception {
  AppConfig appConfig = new AppConfig();
  MongoTemplate mongoTemplate = appConfig.mongoTemplate();
  mongoTemplate.getCollectionNames().forEach(System.out::println);
}

}