1.添加pom依赖
项目使用的springBoot版面本为1.5.7,依赖的mongodb版本为1.10.7
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.mongodb配置文件
配置文件
mongo.address= monggodb地址 例如:localhost:27018
mongo.replica-set=
#database 集合名称
mongo.database=
mongo.username=
mongo.password=
mongo.options.min-connections-per-host=20
mongo.options.max-connections-per-host=20
mongo.options.threads-allowed-to-block-for-connection-multiplier=50
mongo.options.server-selection-timeout=30000
mongo.options.max-wait-time=120000
mongo.options.max-connection-idel-time=0
mongo.options.max-connection-life-time=0
mongo.options.connect-timeout=10000
mongo.options.socket-timeout=0
mongo.options.socket-keep-alive=false
mongo.options.ssl-enabled=false
mongo.options.ssl-invalid-host-name-allowed=false
mongo.options.always-use-m-beans=false
mongo.options.heartbeat-socket-timeout=20000
mongo.options.heartbeat-connect-timeout=20000
mongo.options.min-heartbeat-frequency=500
mongo.options.heartbeat-frequency=10000
mongo.options.local-threshold=15
初始化配置文件MongoDbProperties(代码可滑动查看)
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
/**
* @author Abbot
* @create 2018-08-24 17:05
*/
@ConfigurationProperties(prefix = "mongo")
@PropertySource("classpath:app.properties")
public class MongoDbProperties {
@NotBlank
private String database;
@NotEmpty
private List<String> address;
private String replicaSet;
private String username;
private String password;
private Integer minConnectionsPerHost = 0;
private Integer maxConnectionsPerHost = 100;
private Integer threadsAllowedToBlockForConnectionMultiplier = 5;
private Integer serverSelectionTimeout = 30000;
private Integer maxWaitTime = 120000;
private Integer maxConnectionIdleTime = 0;
private Integer maxConnectionLifeTime = 0;
private Integer connectTimeout = 10000;
private Integer socketTimeout = 0;
private Boolean socketKeepAlive = false;
private Boolean sslEnabled = false;
private Boolean sslInvalidHostNameAllowed = false;
private Boolean alwaysUseMBeans = false;
private Integer heartbeatFrequency = 10000;
private Integer minHeartbeatFrequency = 500;
private Integer heartbeatConnectTimeout = 20000;
private Integer heartbeatSocketTimeout = 20000;
private Integer localThreshold = 15;
private String authenticationDatabase;
//省略getter and setter
}
mongoConfig(代码可左右滑动查看)
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import java.util.ArrayList;
import java.util.List;
/**
* @author by abbot
* @create 2018-08-24 17:19
**/
@Configuration
@EnableConfigurationProperties({MongoDbProperties.class})
public class MongoDbConfig {
@Autowired
MongoDbProperties properties;
@Bean
public MongoDbFactory mongoDbFactory(MongoDbProperties properties) {
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.connectionsPerHost(properties.getMaxConnectionsPerHost());
builder.minConnectionsPerHost(properties.getMinConnectionsPerHost());
if (StringUtils.isNotBlank(properties.getReplicaSet())) {
builder.requiredReplicaSetName(properties.getReplicaSet());
}
builder.threadsAllowedToBlockForConnectionMultiplier(
properties.getThreadsAllowedToBlockForConnectionMultiplier());
builder.serverSelectionTimeout(properties.getServerSelectionTimeout());
builder.maxWaitTime(properties.getMaxWaitTime());
builder.maxConnectionIdleTime(properties.getMaxConnectionIdleTime());
builder.maxConnectionLifeTime(properties.getMaxConnectionLifeTime());
builder.connectTimeout(properties.getConnectTimeout());
builder.socketTimeout(properties.getSocketTimeout());
// builder.socketKeepAlive(properties.getSocketKeepAlive());
builder.sslEnabled(properties.getSslEnabled());
builder.sslInvalidHostNameAllowed(properties.getSslInvalidHostNameAllowed());
builder.alwaysUseMBeans(properties.getAlwaysUseMBeans());
builder.heartbeatFrequency(properties.getHeartbeatFrequency());
builder.minHeartbeatFrequency(properties.getMinHeartbeatFrequency());
builder.heartbeatConnectTimeout(properties.getHeartbeatConnectTimeout());
builder.heartbeatSocketTimeout(properties.getHeartbeatSocketTimeout());
builder.localThreshold(properties.getLocalThreshold());
MongoClientOptions mongoClientOptions = builder.build();
// MongoDB地址列表
List<ServerAddress> serverAddresses = new ArrayList<>();
for (String address : properties.getAddress()) {
String[] hostAndPort = address.split(":");
String host = hostAndPort[0];
Integer port = Integer.parseInt(hostAndPort[1]);
ServerAddress serverAddress = new ServerAddress(host, port);
serverAddresses.add(serverAddress);
}
System.out.println(" MongoDB地址列表serverAddresses:" + serverAddresses.toString());
// 连接认证
List<MongoCredential> mongoCredentialList = new ArrayList<>();
if (StringUtils.isNotBlank(properties.getUsername())) {
mongoCredentialList.add(MongoCredential.createScramSha1Credential(
properties.getUsername(),
StringUtils.isNotBlank(properties.getAuthenticationDatabase()) ? properties.getAuthenticationDatabase() : properties.getDatabase(),
properties.getPassword().toCharArray()));
}
System.out.println("连接认证mongoCredentialList:" + mongoCredentialList.toString());
//创建客户端和Factory
MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredentialList, mongoClientOptions);
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
return mongoDbFactory;
}
@Bean
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
try {
mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
} catch (NoSuchBeanDefinitionException ignore) {
}
//不保存save _class
mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
return mappingConverter;
}
}
3.启动AppliCation
2018-09-10 15:25:48:806:[springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper:120] [main] INFO Context refreshed
2018-09-10 15:25:48:822:[springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper:123] [main] INFO Found 1 custom documentation plugin(s)
2018-09-10 15:25:48:830:[springfox.documentation.spring.web.scanners.ApiListingReferenceScanner:44] [main] INFO Scanning for api listing references
2018-09-10 15:25:49:409:[org.apache.coyote.http11.Http11NioProtocol:179] [main] INFO Initializing ProtocolHandler ["http-nio-8010"]
2018-09-10 15:25:49:421:[org.apache.coyote.http11.Http11NioProtocol:179] [main] INFO Starting ProtocolHandler ["http-nio-8010"]
2018-09-10 15:25:49:434:[org.apache.tomcat.util.net.NioSelectorPool:179] [main] INFO Using a shared selector for servlet write/read
2018-09-10 15:25:49:451:[org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer:201] [main] INFO Tomcat started on port(s): 8010 (http)
2018-09-10 15:25:49:456:[cn.leadeon.hlj.db.HljDbServserApplication:57] [main] INFO Started HljDbServserApplication in 13.911 seconds (JVM running for 17.519)
2018-09-10 15:25:50:085:[org.mongodb.driver.connection:71] [RMI TCP Connection(6)-127.0.0.1] INFO Opened connection [connectionId{localValue:2, serverValue:10186}] to localhost:27018
2018-09-10 15:25:52:953:[com.alibaba.druid.pool.DruidDataSource:715] [RMI TCP Connection(6)-127.0.0.1] INFO {dataSource-1} inited
2018-09-10 15:25:55:710:[com.alibaba.druid.pool.DruidDataSource:715] [RMI TCP Connection(6)-127.0.0.1] INFO {dataSource-2} inited
2018-09-10 15:25:58:439:[com.alibaba.druid.pool.DruidDataSource:715] [RMI TCP Connection(6)-127.0.0.1] INFO {dataSource-3} inited
2018-09-10 15:26:01:252:[com.alibaba.druid.pool.DruidDataSource:715] [RMI TCP Connection(6)-127.0.0.1] INFO {dataSource-4} inited
其中这句我本机映射线上地址表示已经连接上:
2018-09-10 15:25:50:085:[org.mongodb.driver.connection:71] [RMI TCP Connection(6)-127.0.0.1] INFO Opened connection [connectionId{localValue:2, serverValue:10186}] to localhost:27018
4.代码测试
使用Robomongo连接上我们查看数据库有数据,使用swagger2测试代码正确。