单机版本的mongo,直接配置yml 就可以了
今天项目中遇到了需要连接mongo集群的问题,发现直接配置yml是无法实现的,百度了半天依然不行,最后参考了下另外一个成熟项目,尝试扒了下,特此记录;
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
<version>2.3.12.RELEASEversion>
dependency>
spring:
data:
mongodb:
host: 101.61.4.414
port: 27017
username: root
password: root
authentication-database: admin
database: admin
@SpringBootTest
public class MongoTem {
@Autowired
MongoTemplate mongoTemplate;
@SneakyThrows
@Test
void ss() {
Query query = new Query();
query.addCriteria(Criteria.where("type").regex("app"));
// 符合条件的数据
List<Map> maps = mongoTemplate.find(query, Map.class, "111");
}
}
yml如下:
mongodb:
uri: 101.10.66.17:27017,101.10.66.17:27018,101.10.66.16:27017
database: 2222
username: root
password: root
authenticationDatabase: root
pom如下:
springboot 2.7.1
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-mongodbartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>org.mongodbgroupId>
<artifactId>mongodb-driver-syncartifactId>
<version>4.6.1version>
dependency>
代码如下:
@Configuration
public class MongoConfig {
@Value("${mongodb.uri}")
private String mongoUri;
@Value("${mongodb.database}")
private String database;
@Value("${mongodb.username}")
private String username;
@Value("${mongodb.password}")
private String password;
@Value("${mongodb.authenticationDatabase}")
private String authenticationDatabase;
@Bean
public MongoClient mongoClient() throws Exception {
// 初始化连接 用户密码
MongoCredential credential = MongoCredential
.createScramSha256Credential(username, authenticationDatabase, password.toCharArray());
// 解析集群ip:端口配置
List<ServerAddress> serverAddresses = Stream.of(mongoUri.split(","))
.map(cl -> cl.split(":"))
.map(split -> new ServerAddress(split[0], Integer.parseInt(split[1])))
.collect(Collectors.toList());
// 设置MongoClient ip:端口 以及Cluster 类型
Builder builder = MongoClientSettings.builder();
builder.applyToClusterSettings((setting) -> {
setting.hosts(serverAddresses);
setting.requiredClusterType(ClusterType.REPLICA_SET);
}).credential(credential).build();
return new MongoClientImpl(builder.build(),
MongoDriverInformation.builder().driverName("sync").build());
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoClient mongoClient = mongoClient();
// 利用集群配置,重新覆盖MongoTemplate
MongoDatabaseFactorySupport factory = new SimpleMongoClientDatabaseFactory(mongoClient, database);
return new MongoTemplate(factory);
}
}
代码如下:
@SpringBootTest
public class MongoTem {
@Autowired
MongoTemplate mongoTemplate;
@SneakyThrows
@Test
void ss() {
Query query = new Query();
query.addCriteria(Criteria.where("type").regex("app"));
// 符合条件的数据
List<Map> maps = mongoTemplate.find(query, Map.class, "111");
}
}
对于mongo的集群,是不支持直接配置的,需要手动配置,解析集群连接信息,然后重新利用配置的MongoClient,覆盖掉原有的 MongoTemplate,这样就能继续使用 MongoTemplate了;
其中版本需要对应上,此文所用版本为 spring-data-mongodb :3.4.1 mongodb-driver-sync: 4.6.1
文中涉及所有代码: mongo集群连接示例
发现一个连接集群的简化版本:
代码如下:
@Configuration
public class MongoConfig {
@Value("${mongodb.uri}")
private String mongoUri;
@Value("${mongodb.database}")
private String database;
@Value("${mongodb.username}")
private String username;
@Value("${mongodb.password}")
private String password;
@Value("${mongodb.authenticationDatabase}")
private String authenticationDatabase;
/**2. 利用 MongoClients 初始化连接**/
// 标准集群url如下 mongodb://用户名:密码@ip:port,ip:port,ip:port/?验证数据库信息
// mongodb://root:[email protected]:27017,101.10.66.17:27018,101.10.66.16:27017/?authSource=root
@Bean
public MongoClient mongoClient() {
return MongoClients.create(String.format("mongodb://%s:%s@%s/?authSource=%s",username,password,mongoUri,authenticationDatabase));
}
@Bean
public MongoTemplate mongoTemplate(){
return new MongoTemplate(mongoClient(),database);
}
}