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

《spring data mongodb 代码连接数据库方式》要点:
本文介绍了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 UnknownHostException,Exception {

AppConfig appConfig = new AppConfig();

MongoTemplate mongoTemplate = appConfig.mongoTemplate();

mongoTemplate.getCollectionNames().forEach(System.out::println);

}

}

编程之家PHP培训学院每天发布《spring data mongodb 代码连接数据库方式》等实战技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培养人才。

相关文章

文章浏览阅读552次。com.mongodb.MongoQueryException: Quer...
文章浏览阅读635次,点赞9次,收藏8次。MongoDB 是一种 NoSQ...
文章浏览阅读2.1k次。和。_mongodb 日期类型
文章浏览阅读1.7k次。Scalestack等客户期待使用MongoDB Atla...
文章浏览阅读970次。SpringBoot整合中间件mongodb、ES_sprin...
文章浏览阅读673次。MongoDB 简介_尚医通sql