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全面培养人才。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |