连接到 MongoDB
注册 Mongo 实例
以下示例显示了注册 的实例的示例:MongoClient
MongoClient
-
Imperative
-
Reactive
-
XML
@Configuration
public class AppConfig {
/*
* Use the standard Mongo driver API to create a com.mongodb.client.MongoClient instance.
*/
public @Bean com.mongodb.client.MongoClient mongoClient() {
return com.mongodb.client.MongoClients.create("mongodb://localhost:27017");
}
}
@Configuration
public class AppConfig {
/*
* Use the standard Mongo driver API to create a com.mongodb.client.MongoClient instance.
*/
public @Bean com.mongodb.reactivestreams.client.MongoClient mongoClient() {
return com.mongodb.reactivestreams.client.MongoClients.create("mongodb://localhost:27017");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=
"
http://www.springframework.org/schema/data/mongo https://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Default bean name is 'mongo' -->
<mongo:mongo-client host="localhost" port="27017"/>
</beans>
这种方法允许你使用标准实例,容器使用 Spring 的 /.
与直接实例化实例相比,它还具有额外的优势,即还为容器提供了一个实现,该实现将 MongoDB 异常转换为 Spring 的可移植层次结构中的异常,用于使用 Comments 注释的数据访问类。
这种层次结构和的使用在 Spring 的 DAO 支持功能中进行了描述。MongoClient
MongoClientFactoryBean
ReactiveMongoClientFactoryBean
MongoClient
FactoryBean
ExceptionTranslator
DataAccessException
@Repository
@Repository
以下示例显示了一个基于 Java 的 Bean 元数据的示例,该元数据支持对带注释的类进行异常转换:@Repository
MongoClient
MongoClientFactoryBean
/ ReactiveMongoClientFactoryBean
-
Imperative
-
Reactive
@Configuration
public class AppConfig {
/*
* Factory bean that creates the com.mongodb.client.MongoClient instance
*/
public @Bean MongoClientFactoryBean mongo() {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost("localhost");
return mongo;
}
}
@Configuration
public class AppConfig {
/*
* Factory bean that creates the com.mongodb.reactivestreams.client.MongoClient instance
*/
public @Bean ReactiveMongoClientFactoryBean mongo() {
ReactiveMongoClientFactoryBean mongo = new ReactiveMongoClientFactoryBean();
mongo.setHost("localhost");
return mongo;
}
}
要访问由 在其他类或您自己的类中创建的对象,请使用字段。MongoClient
FactoryBean
@Configuration
private @Autowired MongoClient mongoClient;
MongoDatabaseFactory 接口
虽然 是 MongoDB 驱动程序 API 的入口点,但连接到特定的 MongoDB 数据库实例需要其他信息,例如数据库名称以及可选的用户名和密码。
使用该信息,您可以获取对象并访问特定 MongoDB 数据库实例的所有功能。
Spring 提供了 & 接口,如下面的列表所示,用于引导与数据库的连接:MongoClient
MongoDatabase
org.springframework.data.mongodb.core.MongoDatabaseFactory
org.springframework.data.mongodb.core.ReactiveMongoDatabaseFactory
-
Imperative
-
Reactive
public interface MongoDatabaseFactory {
MongoDatabase getDatabase() throws DataAccessException;
MongoDatabase getDatabase(String dbName) throws DataAccessException;
}
public interface ReactiveMongoDatabaseFactory {
Mono<MongoDatabase> getDatabase() throws DataAccessException;
Mono<MongoDatabase> getDatabase(String dbName) throws DataAccessException;
}
以下部分介绍如何使用具有基于 Java 或基于 XML 的元数据的容器来配置接口实例。
反过来,您可以使用 / 实例配置 / 。MongoDatabaseFactory
MongoDatabaseFactory
ReactiveMongoDatabaseFactory
MongoTemplate
ReactiveMongoTemplate
您可以在标准 Java 代码中使用它们,而不是使用 IoC 容器来创建模板的实例,如下所示:
-
Imperative
-
Reactive
public class MongoApplication {
public static void main(String[] args) throws Exception {
MongoOperations mongoOps = new MongoTemplate(new SimpleMongoClientDatabaseFactory(MongoClients.create(), "database"));
// ...
}
}
粗体代码突出显示了 和 的用法,这是 入门 部分中显示的列表之间的唯一区别。
在选择作为所选入口点时使用。SimpleMongoClientDbFactory
SimpleMongoClientDbFactory
com.mongodb.client.MongoClient
public class ReactiveMongoApplication {
public static void main(String[] args) throws Exception {
ReactiveMongoOperations mongoOps = new MongoTemplate(new SimpleReactiveMongoDatabaseFactory(MongoClients.create(), "database"));
// ...
}
}
注册MongoDatabaseFactory
/ ReactiveMongoDatabaseFactory
要向容器注册 / 实例,您需要编写与上一节中重点介绍的代码非常相似的代码。
下面的清单显示了一个简单的示例:MongoDatabaseFactory
ReactiveMongoDatabaseFactory
-
Imperative
-
Reactive
@Configuration
public class MongoConfiguration {
@Bean
public MongoDatabaseFactory mongoDatabaseFactory() {
return new SimpleMongoClientDatabaseFactory(MongoClients.create(), "database");
}
}
@Configuration
public class ReactiveMongoConfiguration {
@Bean
public ReactiveMongoDatabaseFactory mongoDatabaseFactory() {
return new SimpleReactiveMongoDatabaseFactory(MongoClients.create(), "database");
}
}
MongoDB Server 第 3 代在连接到 DB 时更改了身份验证模型。
因此,某些可用于身份验证的配置选项不再有效。
您应该使用 -specific 选项来设置凭证,以提供身份验证数据,如以下示例所示:MongoClient
MongoCredential
-
Java
-
XML
@Configuration
public class MongoAppConfig extends AbstractMongoClientConfiguration {
@Override
public String getDatabaseName() {
return "database";
}
@Override
protected void configureClientSettings(Builder builder) {
builder
.credential(MongoCredential.createCredential("name", "db", "pwd".toCharArray()))
.applyToClusterSettings(settings -> {
settings.hosts(singletonList(new ServerAddress("127.0.0.1", 27017)));
});
}
}
<mongo:db-factory dbname="database" />
当基于 XML 的配置中使用的用户名和密码凭据包含保留字符(如 、 、 或 )时,必须对这些凭据进行 URL 编码。
以下示例显示了编码的凭据:→ 有关更多详细信息,请参阅 RFC 3986 的第 2.2 节。:
%
@
,
m0ng0@dmin:mo_res:bw6},Qsdxx@admin@database
m0ng0%40dmin:mo_res%3Abw6%7D%2CQsdxx%40admin@database
如果需要在用于创建 的实例上配置其他选项,则可以引用现有 Bean,如以下示例所示。为了显示另一种常见的使用模式,下面的清单显示了属性占位符的用法,它允许您参数化配置和创建:com.mongodb.client.MongoClient
SimpleMongoClientDbFactory
MongoTemplate
-
Java
-
XML
@Configuration
@PropertySource("classpath:/com/myapp/mongodb/config/mongo.properties")
public class MongoAppConfig extends AbstractMongoClientConfiguration {
@Autowired
Environment env;
@Override
public String getDatabaseName() {
return "database";
}
@Override
protected void configureClientSettings(Builder builder) {
builder.applyToClusterSettings(settings -> {
settings.hosts(singletonList(
new ServerAddress(env.getProperty("mongo.host"), env.getProperty("mongo.port", Integer.class))));
});
builder.applyToConnectionPoolSettings(settings -> {
settings.maxConnectionLifeTime(env.getProperty("mongo.pool-max-life-time", Integer.class), TimeUnit.MILLISECONDS)
.minSize(env.getProperty("mongo.pool-min-size", Integer.class))
.maxSize(env.getProperty("mongo.pool-max-size", Integer.class))
.maintenanceFrequency(10, TimeUnit.MILLISECONDS)
.maintenanceInitialDelay(11, TimeUnit.MILLISECONDS)
.maxConnectionIdleTime(30, TimeUnit.SECONDS)
.maxWaitTime(15, TimeUnit.MILLISECONDS);
});
}
}
<context:property-placeholder location="classpath:/com/myapp/mongodb/config/mongo.properties"/>
<mongo:mongo-client host="${mongo.host}" port="${mongo.port}">
<mongo:client-settings connection-pool-max-connection-life-time="${mongo.pool-max-life-time}"
connection-pool-min-size="${mongo.pool-min-size}"
connection-pool-max-size="${mongo.pool-max-size}"
connection-pool-maintenance-frequency="10"
connection-pool-maintenance-initial-delay="11"
connection-pool-max-connection-idle-time="30"
connection-pool-max-wait-time="15" />
</mongo:mongo-client>
<mongo:db-factory dbname="database" mongo-ref="mongoClient"/>
<bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>