0%

MongoDb 单数据源&多数据源配置

如何配置MongoDb数据源

Spring Boot 使用 MongoDB

Maven

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Repository

1
2
3
4
public interface PersonRepository extends MongoRepository<Person,String> {
Person findByName(String name);
List<Person> findByAge(Integer age);
}

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootTest
@RunWith(SpringRunner.class)
public class MongoDBTest {
@Autowired
private PersonRepository personRepository;

@Test
public void test(){
personRepository.deleteAll();
personRepository.save(new Person("zhangsan",4));
personRepository.save(new Person("wangwu",4));
System.out.println(personRepository.findByAge(4));
}
}
//[Person{name='zhangsan', age=4}, Person{name='wangwu', age=4}]

application.properties

1
spring.data.mongodb.uri=mongodb://120.*.*.*:27017/local

Spring Boot Mongo多数据源

Maven

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

MultipleMongoProperties.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class MultipleMongoProperties {
@Bean(name="firstMongoProperties")
@ConfigurationProperties(prefix="spring.data.mongodb.first")
public MongoProperties firstMongoProperties() {
return new MongoProperties();
}

@Bean(name="secondMongoProperties")
@ConfigurationProperties(prefix="spring.data.mongodb.second")
public MongoProperties secondMongoProperties() {
return new MongoProperties();
}
}

MongoTemplate.java(方法一)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@Configuration
@EnableMongoRepositories(mongoTemplateRef = "firstMongo")
public class FirstMongoTemplate {

private MongoProperties mongoProperties;

@Bean(name = "firstMongo")
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(getMongoDbFactory(this.mongoProperties));
}

@Bean("firstMongoDbFactory")
public MongoDbFactory getMongoDbFactory(@Qualifier("firstMongoProperties") MongoProperties mongoProperties) {
ServerAddress serverAdress = new ServerAddress(mongoProperties.getHost(),mongoProperties.getPort());
if (!ObjectUtils.isEmpty(mongoProperties.getUsername())
&& !ObjectUtils.isEmpty(mongoProperties.getPassword())) {
MongoCredential credential = MongoCredential.createCredential(
mongoProperties.getUsername(),
mongoProperties.getDatabase(),
mongoProperties.getPassword());
return new SimpleMongoDbFactory(new MongoClient(serverAdress, credential, MongoClientOptions.builder().build()), mongoProperties.getDatabase());
} else {
return new SimpleMongoDbFactory(new MongoClient(serverAdress), mongoProperties.getDatabase());
}
}

}

@Configuration
@EnableMongoRepositories(mongoTemplateRef = "secondMongo")
public class SecondMongoTemplate {

private MongoProperties mongoProperties;

@Bean(name = "secondMongo")
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(getMongoDbFactory(this.mongoProperties));
}

@Bean("secondMongoDbFactory")
public MongoDbFactory getMongoDbFactory(@Qualifier("secondMongoProperties") MongoProperties mongoProperties) {
ServerAddress serverAdress = new ServerAddress(mongoProperties.getHost(),mongoProperties.getPort());
if (!ObjectUtils.isEmpty(mongoProperties.getUsername())
&& !ObjectUtils.isEmpty(mongoProperties.getPassword())) {
MongoCredential credential = MongoCredential.createCredential(
mongoProperties.getUsername(),
mongoProperties.getDatabase(),
mongoProperties.getPassword());
return new SimpleMongoDbFactory(new MongoClient(serverAdress, credential, MongoClientOptions.builder().build()), mongoProperties.getDatabase());
} else {
return new SimpleMongoDbFactory(new MongoClient(serverAdress), mongoProperties.getDatabase());
}
}
}

application.properties(方法一)

1
2
3
4
5
6
7
8
9
10
11
spring.data.mongodb.first.host=120.*.*.*
spring.data.mongodb.first.port=27017
spring.data.mongodb.first.database=local
#spring.data.mongodb.first.username=
#spring.data.mongodb.first.password=

spring.data.mongodb.second.host=120.*.*.*
spring.data.mongodb.second.port=3717
spring.data.mongodb.second.database=admin
spring.data.mongodb.second.username=root
spring.data.mongodb.second.password=******

MongoTemplate.java(方法二)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Configuration
@EnableMongoRepositories(mongoTemplateRef = "firstMongo")
public class FirstMongoTemplate {

@Value("${spring.data.mongodb.first.uri}")
private String mongoUri;

@Bean(name = "firstMongo")
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(getMongoDbFactory());
}

@Bean("firstMongoDbFactory")
public MongoDbFactory getMongoDbFactory() {
return new SimpleMongoDbFactory(new MongoClientURI(mongoUri));
}

}

@Configuration
@EnableMongoRepositories(mongoTemplateRef = "secondMongo")
public class SecondMongoTemplate {

@Value("${spring.data.mongodb.second.uri}")
private String mongoUri;

@Bean(name = "secondMongo")
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(getMongoDbFactory(this.mongoProperties));
}

@Bean("secondMongoDbFactory")
public MongoDbFactory getMongoDbFactory() {
return new SimpleMongoDbFactory(new MongoClientURI(mongoUri));
}
}

application.properties(方法二)

1
2
spring.data.mongodb.first.uri=mongodb://root:fd3t8gfHGDgfdsa03t@120.77.183.88:3717/nfapp_dev
spring.data.mongodb.second.uri=mongodb://120.79.28.55:27017/local

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RunWith(SpringRunner.class)
@SpringBootTest
public class NfplusSubscriptionCenterApplicationTests {
@Resource(name="firstMongo")
private MongoTemplate firstMongoTemplate;
@Resource(name="secondMongo")
private MongoTemplate secondMongoTemplate;

@Test
public void mongoTest() {
firstMongoTemplate.insert(new Person("zhangsan", 3),"personList");
List<Person> personList = firstMongoTemplate.findAll(Person.class,"personList");
System.out.println("personList:"+personList);
System.out.println("secondMongo:"+secondMongoTemplate.findAll(Person.class));
personList.forEach(person -> firstMongoTemplate.remove(person));
}
}

Spring Framwork 使用 MongoDB

Maven

1
2
3
4
5
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>RELEASE</version>
</dependency>

mongo.properties

1
2
3
4
5
mongo.database=local
mongo.host=120.79.28.55
mongo.port=27017
mongo.user=
mongo.password=

MongoConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Configuration
@PropertySource(value = "classpath:configs/mongo.properties", encoding = "UTF-8")
public class MongoConfig {

@Bean
public MongoClientFactoryBean mongoClientFactoryBean(Environment env) {
MongoCredential credential = MongoCredential.createCredential(
env.getProperty("mongo.user", String.class),
env.getProperty("mongo.database", String.class)
, env.getProperty("mongo.password", String.class) .toCharArray()
);
//没有账号密码可以不添加认证
//mongoClientFactoryBean.setCredentials(new MongoCredential[]{credential});
MongoClientFactoryBean mongoClientFactoryBean = new MongoClientFactoryBean();
mongoClientFactoryBean.setHost(env.getProperty("mongo.host", String.class));
mongoClientFactoryBean.setPort(env.getProperty("mongo.port", Integer.class));
return mongoClientFactoryBean;
}

@Bean
public MongoTemplate mongoTemplate(MongoClientFactoryBean mongoClientFactoryBean, Environment env) throws Exception {
return new MongoTemplate(mongoClientFactoryBean.getObject(), env.getProperty("mongo.database", String.class));
}
}

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
public class MogoController {
@Autowired
private MongoTemplate mongoTemplate;

@GetMapping("testMogo")
public Object test(){
Vote vote = new Vote();
vote.setId(1);
vote.setTitle("测试mogo");
mongoTemplate.insert(vote);
return mongoTemplate.findAll(Vote.class);
}
}

//[{"id": 1,"title": "测试mogo"}]