SpringBoot集成MongoDb

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测试代码正确。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,080评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,422评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,630评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,554评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,662评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,856评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,014评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,752评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,212评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,541评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,687评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,347评论 4 331
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,973评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,777评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,006评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,406评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,576评论 2 349

推荐阅读更多精彩内容