1、 添加MAVEN配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>${spring.version}</version>
</dependency>
2、yaml配置
spring.data.mongodb.uri=mongodb://username:password@ip1,ip2:27017/test
3、扩展配置
@Configuration
public class MongoConfiguration {
@Bean
public MongoClientOptions mongoClientOptions(MongoOptionProperties mongoOptionProperties) {
if (mongoOptionProperties == null) {
return new MongoClientOptions.Builder().build();
}
return new MongoClientOptions.Builder()
.minConnectionsPerHost(0)
.connectionsPerHost(100)
.threadsAllowedToBlockForConnectionMultiplier(5)
.serverSelectionTimeout(30000)
.maxWaitTime(120000)
.maxConnectionIdleTime(0)
.maxConnectionLifeTime(0)
.connectTimeout(10000)
.socketTimeout(0)
.socketKeepAlive(false)
.sslEnabled(false)
.sslInvalidHostNameAllowed(false)
.alwaysUseMBeans(false)
.heartbeatFrequency(500)
.heartbeatConnectTimeout(20000)
.heartbeatSocketTimeout(20000)
.localThreshold(15)
.build();
}
}
4、添加Main入口
@SpringBootApplication
class ApplicationConfiguration {
public @Bean LoggingEventListener mongoEventListener() {
return new LoggingEventListener();
}
}
5、添加POJO
@Data
@RequiredArgsConstructor
public class Person {
private @Id String id;
private final String firstname;
private final String lastname;
}
6、建立单元测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationConfiguration.class)
public class MongoTemplateTest {
Person dave, oliver, carter;
@Autowired
MongoOperations mongoOps;
@Before
public void setUp() {
mongoOps.remove(new Query(),Person.class);
dave = mongoOps.insert(new Person("Dave", "Matthews"));
oliver = mongoOps.insert(new Person("Oliver August", "Matthews"));
carter = mongoOps.insert(new Person("Carter", "Beauford"));
}
@Test
public void testTemplate(){
mongoOps.findAll(Person.class).forEach(System.out::println);
}
}
输出结果:
Person(id=5c3c51d508a7f52308f7166c, firstname=Dave, lastname=Matthews)
Person(id=5c3c51d508a7f52308f7166d, firstname=Oliver August, lastname=Matthews)
Person(id=5c3c51d508a7f52308f7166e, firstname=Carter, lastname=Beauford)