Springboot自定義配置Mongodb數據源

該篇文章配置的Mongodb數據源的背景是在多數據源的情況下——已經配置了倆個Mysql的數據源。如果僅僅只需要配置一個mongodb數據源,那麼就非常簡單,配置文件裏面添上mongodb的host,port,database(主機,端口號,數據庫名),之後使用Springboot的自動化配置,直接注入MongoTemplate就能夠進行操作。

而如果在已經配置了其他數據源的情況下(多數據源都是自定義配置),就需要自己手動配置需要的bean了。

源代碼地址:https://github.com/AliceAsuna/KiritoV1.git

一、配置文件

spring:
  datasource:
    test1:
        jdbc-url: jdbc:mysql://localhost:3306/alice_test?serverTimezone=CTT&useUnicode=true&characterEncoding=utf8
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: xxx
    test2:
        jdbc-url: jdbc:mysql://localhost:3306/alice_test_two?serverTimezone=CTT&useUnicode=true&characterEncoding=utf8
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: xxx
    mongodb:
        host: 127.0.0.1
        port: 27017
        database: own_test_mongodb

mybatis:
  mapper-locations: classpath:*/mapper/**.xml

二、Mongodb配置類

Mysql配置類在上一篇文章(Springboot整合Mybatis多數據源配置)中提及,這裏就不在展示代碼

package com.alice.springboot.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class MongoConfig {
    @Value("${spring.datasource.mongodb.host}")
    private String host;

    @Value("${spring.datasource.mongodb.port}")
    private int port;

    @Value("${spring.datasource.mongodb.database}")
    private String database;

    @Bean(name = "mongoDbFactory")
    public MongoDbFactory mongoDbFactory() {

        // 客戶端
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectTimeout(10000);
        builder.maxWaitTime(120000);

        //數據庫連接池其他參數,如最大連接數這些,可以參考着使用部分參數
        //builder.connectionsPerHost();
        //builder.minConnectionsPerHost();
        //builder.requiredReplicaSetName();
        //builder.threadsAllowedToBlockForConnectionMultiplier();
        //builder.serverSelectionTimeout();
        //builder.maxConnectionIdleTime();
        //builder.maxConnectionLifeTime();
        //builder.socketTimeout());
        //builder.socketKeepAlive();
        //builder.sslEnabled());
        //builder.sslInvalidHostNameAllowed();
        //builder.alwaysUseMBeans();
        //builder.heartbeatFrequency();
        //builder.minHeartbeatFrequency();
        //builder.heartbeatConnectTimeout();
        //builder.heartbeatSocketTimeout();
        //builder.localThreshold();

        MongoClientOptions mongoClientOptions = builder.build();

        // MongoDB地址列表,如果有多個ip地址,那麼配置文件裏面可以用逗號分隔ip地址,這裏再把每一個ip地址和端口號添加進list裏面
        List<ServerAddress> serverAddresses = new ArrayList<>();
        ServerAddress serverAddress = new ServerAddress(host, port);
        serverAddresses.add(serverAddress);

        // 連接認證,如果設置了用戶名和密碼的話
        // MongoCredential mongoCredential = null;
        // mongoCredential = MongoCredential.createScramSha1Credential();

        // 創建認證客戶端(存在用戶名和密碼)
        // MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, mongoClientOptions);

        // 創建非認證客戶端(沒有設置mongodb數據庫的用戶名和密碼)
        MongoClient mongoClient = new MongoClient(serverAddresses, mongoClientOptions);

        // 創建MongoDbFactory
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, database);
        return mongoDbFactory;
    }

    @Bean(name = "mongoTemplate")
    @Autowired
    public MongoTemplate getMongoTemplate(MongoDbFactory mongoDbFactory)
    {
        return new MongoTemplate(mongoDbFactory);
    }
}

三、Dao層

這裏只展示dao實現層,接口層就不貼出來了

package com.alice.springboot.dao.impl;

import com.alice.springboot.dao.IMongoCommonDao;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MongoCommonDaoImpl implements IMongoCommonDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    private MongoCollection<Document> getCollection(String collectionName)
    {
        return mongoTemplate.getCollection(collectionName);
    }

    @Override
    public void saveDataToMongoDB(String collectionName, Document document) {
        MongoCollection<Document> collection = getCollection(collectionName);
        collection.insertOne(new Document().append("test", "測試保存數據"));
    }
}

四、controller層

實際上應該是在service層調用dao層,這裏爲了測試,就直接在controller用dao層了

package com.alice.springboot.controller;

import com.alice.springboot.constants.ResponseStatusEnum;
import com.alice.springboot.dao.IMongoCommonDao;
import com.alice.springboot.model.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1")
public class MongoDBTestController {
    @Autowired
    private IMongoCommonDao mongoCommonDao;

    @RequestMapping(value = "/test/mongo/person", method = RequestMethod.GET)
    public ResponseResult<String> testMongo()
    {
        ResponseResult<String> result = new ResponseResult<>();
        try
        {
            mongoCommonDao.saveDataToMongoDB("just_for_test", null);
            result.setMessage("成功測試鏈接mongodb");
            result.setStatus(ResponseStatusEnum.SUCCESS);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }
}

爲了測試,接口也沒有按照restful接口規範來,保存數據應該用Post方法。

五、響應結果

{"status":"SUCCESS","other":null,"message":"成功測試鏈接mongodb","code":"200","params":[],"data":null}

六、數據庫數據

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章