Rely on

// build.gradle

implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
Copy the code

The configuration file

# application.yml

spring:
  data:
    mongodb:
      primary:
        uri: mongodb://localhost:27017/db1
      secondary:
        uri: mongodb://localhost:27017/db2
Copy the code

Primary database Configuration

// PrimaryMongoConfig.java

package com.fengwenyi.springboot_mongo_multi_source.config;

import com.mongodb.MongoClientURI;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * MongoDB Primary Config
 * @author Erwin Feng
 * @sinceThe 2019-07-01 "* /
@Configuration
@EnableMongoRepositories(basePackages = "com.fengwenyi.springboot_mongo_multi_source.primary",
        mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix="spring.data.mongodb.primary")
    public MongoProperties primaryMongoProperties(a) {
        return new MongoProperties();
    }

    @Primary
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate primaryMongoTemplate(a) throws Exception {
        return new MongoTemplate(primaryFactory(primaryMongoProperties()));
    }

    @Bean
    @Primary
    public MongoDbFactory primaryFactory(MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoDbFactory(newMongoClientURI(primaryMongoProperties().getUri())); }}Copy the code

Secondary database configuration

// SecondaryMongoConfig.java

package com.fengwenyi.springboot_mongo_multi_source.config;

import com.mongodb.MongoClientURI;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * MongoDB Secondary Config
 * @author Erwin Feng
 * @sinceThe 2019-07-01 "* /
@Configuration
@EnableMongoRepositories(basePackages = "com.fengwenyi.springboot_mongo_multi_source.secondary",
        mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig {

    @Bean
    @ConfigurationProperties(prefix="spring.data.mongodb.secondary")
    public MongoProperties secondaryMongoProperties(a) {
        return new MongoProperties();
    }

    @Bean(name = "secondaryMongoTemplate")
    public MongoTemplate secondaryMongoTemplate(a) throws Exception {
        return new MongoTemplate(secondaryFactory(secondaryMongoProperties()));
    }

    @Bean
    public MongoDbFactory secondaryFactory(MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoDbFactory(newMongoClientURI(secondaryMongoProperties().getUri())); }}Copy the code

User entity, deputy

// User.java

package com.fengwenyi.springboot_mongo_multi_source.secondary.entity;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;
import java.time.Instant;

/** * user *@author Erwin Feng
 * @sinceIn 2019-07-01 he * /
@Data
@Accessors(chain = true)
@Document(collection = "t_user")
public class User implements Serializable {

    private static final long serialVersionUID = -7229906944062898852L;

    /** ID */
    @Id
    private String id;

    /** User name */
    private String username;

    / * * * / age
    private Integer age;

    /** Registration time */
    private Instant registerTime;
}
Copy the code

User query warehouse, vice

// UserRepository.java

package com.fengwenyi.springboot_mongo_multi_source.secondary.repository;

import com.fengwenyi.springboot_mongo_multi_source.secondary.entity.User;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

/** * user *@author Erwin Feng
 * @sinceThe 2019-07-01 was * /
public interface UserRepository extends MongoRepository<User.String> {

    /** * Query by username *@paramUsername username *@return* /
    List<User> findAllByUsername(String username);

}
Copy the code

Logon log entity, master

// LoginLog.java

package com.fengwenyi.springboot_mongo_multi_source.primary.entity;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;

import java.io.Serializable;
import java.time.Instant;

/** * Login log *@author Erwin Feng
 * @sinceThe 2019-07-01 was * /
@Data
@Accessors(chain = true)
public class LoginLog implements Serializable {

    private static final long serialVersionUID = -6694661682102504919L;

    /** ID */
    @Id
    private String id;

    /** user ID */
    private String uid;

    /** User name */
    private String username;

    /** Login time */
    private Instant loginTime;
}
Copy the code

Log in log query warehouse, master

// LoginLogRepository.java

package com.fengwenyi.springboot_mongo_multi_source.primary.repository;

import com.fengwenyi.springboot_mongo_multi_source.primary.entity.LoginLog;
import org.springframework.data.mongodb.repository.MongoRepository;

/** * Login log *@author Erwin Feng
 * @sinceThe 2019-07-01 time * /
public interface LoginLogRepository extends MongoRepository<LoginLog.String> {}Copy the code

Initialize the

// InitController.java

package com.fengwenyi.springboot_mongo_multi_source.controller;

import com.fengwenyi.springboot_mongo_multi_source.secondary.entity.User;
import com.fengwenyi.springboot_mongo_multi_source.secondary.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/** ** *@author Erwin Feng
 * @sinceThe 2019-07-01 cuthah * /
@RestController
public class InitController {

    /** [mongo] user */
    @Autowired
    private UserRepository userRepository;

    @PostConstruct
    public void init(a) {
        List<User> all = userRepository.findAll();
        if (all.size() > 0)
            return;
        userRepository.save(new User().setUsername("Zhangsan").setAge(20).setRegisterTime(Instant.now()));
        List<User> users = new ArrayList<>();
        User u1 = new User().setUsername("u1").setAge(19).setRegisterTime(Instant.now());
        User u2 = new User().setUsername("u2").setAge(20).setRegisterTime(Instant.now());
        User u3 = new User().setUsername("u3").setAge(10).setRegisterTime(Instant.now()); users.add(u1); users.add(u2); users.add(u3); userRepository.saveAll(users); }}Copy the code

The test code

// TestController.java

package com.fengwenyi.springboot_mongo_multi_source.controller;

import com.fengwenyi.springboot_mongo_multi_source.primary.entity.LoginLog;
import com.fengwenyi.springboot_mongo_multi_source.primary.repository.LoginLogRepository;
import com.fengwenyi.springboot_mongo_multi_source.secondary.entity.User;
import com.fengwenyi.springboot_mongo_multi_source.secondary.repository.UserRepository;
import net.iutil.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.List;

/** * test *@author Erwin Feng
 * @sinceThe 2019-07-01 17:28 * /
@RestController
@RequestMapping("/test")
public class TestController {

    /** [mongo] user */
    @Autowired
    private UserRepository userRepository;

    /** [mongo] */
    @Autowired
    private LoginLogRepository loginLogRepository;

    /** [mongo] */
    @Autowired
    private MongoTemplate mongoTemplate;

    /** * login *@param username
     * @return* /
    @GetMapping("/login")
    public ApiResult login(String username) {
        if (StringUtils.isEmpty(username))
            return ApiResult.error().setMsg("User name cannot be empty");
        List<User> users = userRepository.findAllByUsername(username);
        if (users.size() == 1) {
            // Log
            loginLogRepository.save(new LoginLog().setUid(users.get(0).getId()).setUsername(username).setLoginTime(Instant.now()));
            return ApiResult.success();
        }
        if (users.size() == 0)
            return ApiResult.error().setMsg("User name query failed");

        return ApiResult.error().setMsg("User exception");
    }

    /** * Login log *@return* /
    @GetMapping("/login-log")
    public ApiResult loginLog(a) {
        Query query = new Query();
        List<LoginLog> loginLogs = mongoTemplate.find(query, LoginLog.class);
        returnApiResult.success(loginLogs); }}Copy the code

Test user login

GET http://localhost:8080/test/login? username=Zhangsan

Response:

{
    "code": 0."msg": "Success"
}
Copy the code

Test Login Log

GET http://localhost:8080/test/login-log

Response:

{
    "code": 0."msg": "Success"."data": [{"id": "5d19d7f5cede54c46b6b20c5"."uid": "5d19d560cede54c45701e12a"."username": "Zhangsan"."loginTime": "The 2019-07-01 T09:52:53. 447 z"
        },
        {
            "id": "5d19da82cede54c46f77579a"."uid": "5d19d560cede54c45701e12a"."username": "Zhangsan"."loginTime": "The 2019-07-01 T10:03:46. 496 z"
        },
        {
            "id": "5d19df5fcede54c46f77579b"."uid": "5d19d560cede54c45701e12a"."username": "Zhangsan"."loginTime": "The 2019-07-01 T10:24:31. 272 z"
        },
        {
            "id": "5d19df6acede54c46f77579c"."uid": "5d19d560cede54c45701e12b"."username": "u1"."loginTime": "The 2019-07-01 T10:24:42". 199 z"
        },
        {
            "id": "5d19df6dcede54c46f77579d"."uid": "5d19d560cede54c45701e12d"."username": "u3"."loginTime": "The 2019-07-01 T10: then 421 z"}}]Copy the code

code

springboot-mongo-multi-source