当前位置: 首页 > news >正文

springboot 简单配置mongodb多数据源

准备工作:

  1. 本地mongodb一个
  2. 创建两个数据库 student 和 student-two

所需jar包:

# springboot基于的版本
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.1.RELEASE</version><relativePath/>
</parent># maven 关键jar包
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional>
</dependency>

配置文件:

# uri 配置样例: mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/admin 
# 如果用户名或密码包含at符号@,冒号:,斜杠/或百分号%字符,请使用百分比编码方式消除歧义
# uri 集群配置样例: mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl
douzi:mongo:primary:uri: mongodb://127.0.0.1:27017/studentrepository-package: com.douzi.mongo.dao.primarysecondary:uri: mongodb://127.0.0.1:27017/student-tworepository-package: com.douzi.mongo.dao.secondary

多数据源配置类 MultipleMongoConfig:

package com.douzi.mongo.config;import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.util.StringUtils;import com.mongodb.MongoClientURI;/*** @Author douzi* @Title: MultipleMongoConfig* @Description: 读取对应的配置信息并且构造对应的MongoTemplate* @Date 2023-09-27*/
@Configuration
public class MultipleMongoConfig {@Value("${douzi.mongo.primary.uri}")private String primaryUri;@Value("${douzi.mongo.secondary.uri}")private String secondaryUri;/*** 配置主数据源template* @return 主数据源template*/@Primary@Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)public MongoTemplate primaryMongoTemplate() {return new MongoTemplate(primaryFactory());}/*** 配置从数据源template* @return 从数据源template*/@Bean@Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)public MongoTemplate secondaryMongoTemplate() {return new MongoTemplate(secondaryFactory());}/*** 配置主数据源db工厂* @param mongo 属性配置信息* @return 主数据源db工厂*/@Bean@Primarypublic MongoDbFactory primaryFactory() {if (StringUtils.isEmpty(primaryUri)) {throw new RuntimeException("必须配置mongo primary Uri");}return new SimpleMongoDbFactory(new MongoClientURI(primaryUri));}/*** 配置从数据源db工厂* @param mongo 属性配置信息* @return 从数据源db工厂*/@Beanpublic MongoDbFactory secondaryFactory() {return new SimpleMongoDbFactory(new MongoClientURI(secondaryUri));}
}

 主数据源配置 PrimaryMongoConfig:

package com.douzi.mongo.config;import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;/*** @Author douzi* @Title: PrimaryMongoConfig* @Description: 主数据源配置* @date 2023-09-27 */
@Configuration
@EnableMongoRepositories(basePackages = "${douzi.mongo.primary.repository-package}", mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
public class PrimaryMongoConfig {protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
}

副数据源配置 SecondaryMongoConfig:

package com.douzi.mongo.config;import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;/*** @Author douzi* @Title: SecondaryMongoConfig* @Description: 从数据源配置* @Date 2023-09-27*/
@Configuration
@EnableMongoRepositories(basePackages = "${douzi.mongo.secondary.repository-package}", mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
public class SecondaryMongoConfig {protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
}

以下是辅助测试类 高手可以自行测试:

dao层:

package com.douzi.mongo.dao.primary;import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;/*** @Author douzi* @Title: PrimaryStudent* @Description: 主数据源学生对象* @Date 2023/09/24 13:33*/
@Data
@Document(collection = "first_students")
public class PrimaryStudent implements Serializable {/*** id*/@Idprivate Integer id;/*** 姓名*/private String name;/*** 生活费*/private BigDecimal salary;/*** 生日*/private Date birth;}##################################分隔符########################################package com.douzi.mongo.dao.primary;import org.springframework.data.mongodb.repository.MongoRepository;/*** @Author douzi* @Title: PrimaryRepository* @Description: 主数据源dao层* @Date 2023/09/24 16:01*/
public interface PrimaryRepository extends MongoRepository<PrimaryStudent, Integer> {/*** 通过名字查找学生** @param name 名字* @return 学生信息*/PrimaryStudent findByName(String name);/*** 通过名字删除学生** @param name 名字* @return 学生信息*/PrimaryStudent removeStudentByName(String name);
}##################################分隔符########################################package com.douzi.mongo.dao.secondary;import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;/*** * @Author douzi* @Title: PrimaryStudent* @Description: 副数据源学生对象* @Date 2023/09/24 13:33*/
@Data
@Document(collection = "secondary_students")
public class SecondaryStudent implements Serializable {/*** id*/@Idprivate Integer id;/*** 姓名*/private String name;/*** 生活费*/private BigDecimal salary;/*** 生日*/private Date birth;}##################################分隔符########################################package com.douzi.mongo.dao.secondary;import org.springframework.data.mongodb.repository.MongoRepository;/*** @Author douzi* @Title: SecondaryRepository* @Description: 从数据源dao层* @Date 2023/09/24 16:02*/
public interface SecondaryRepository extends MongoRepository<SecondaryStudent, Integer> {/*** 通过名字查找学生** @param name 名字* @return 学生信息*/SecondaryStudent findByName(String name);/*** 通过名字删除学生** @param name 名字* @return 学生信息*/SecondaryStudent removeStudentByName(String name);
}

Service层:

package com.douzi.mongo.service;import com.douzi.mongo.dao.primary.PrimaryRepository;
import com.douzi.mongo.dao.primary.PrimaryStudent;
import com.douzi.mongo.dao.secondary.SecondaryRepository;
import com.douzi.mongo.dao.secondary.SecondaryStudent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** * @Author douzi* @Title: StudentService* @Description: * @Date 2023/09/24 14:32*/
@Service
@Slf4j
public class StudentService {@Autowiredprivate PrimaryRepository primaryRepository;@Autowiredprivate SecondaryRepository secondaryRepository;/*** 保存学生** @param primaryStudent* @param secondaryStudent*/public void save(PrimaryStudent primaryStudent, SecondaryStudent secondaryStudent) {PrimaryStudent student1 = primaryRepository.insert(primaryStudent);log.info(student1.toString());SecondaryStudent student2 = secondaryRepository.insert(secondaryStudent);log.info(student2.toString());}/*** 删除学生** @param name* @return*/public void delete(String name) {primaryRepository.deleteById(1);secondaryRepository.deleteById(1);}/*** 修改学生** @param primaryStudent* @param secondaryStudent*/public void update(PrimaryStudent primaryStudent, SecondaryStudent secondaryStudent) {PrimaryStudent student1 = primaryRepository.save(primaryStudent);log.info(student1.toString());SecondaryStudent student2 = secondaryRepository.save(secondaryStudent);log.info(student2.toString());}/*** 查找学生** @param name 学生姓名* @return*/public void find(String name) {PrimaryStudent student1 = primaryRepository.findByName(name);log.info(student1.toString());SecondaryStudent student2 = secondaryRepository.findByName(name);log.info(student2.toString());}/*** 查找学生集合** @return 学生集合*/public void findAll() {List<PrimaryStudent> primaryRepositoryAll = primaryRepository.findAll();log.info(primaryRepositoryAll.toString());List<SecondaryStudent> secondaryRepositoryAll = secondaryRepository.findAll();log.info(secondaryRepositoryAll.toString());}
}

Controller层:

package com.douzi.mongo.controller;import com.douzi.mongo.dao.primary.PrimaryStudent;
import com.douzi.mongo.dao.secondary.SecondaryStudent;
import com.douzi.mongo.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.math.BigDecimal;
import java.util.Date;/*** @Author douzi* @Title: StudentController* @Description: * @Date 2023/09/24 14:53*/
@RestController
@RequestMapping("/student")
public class StudentController {@Autowiredprivate StudentService studentService;/*** 保存学生** @return 保存的学生*/@RequestMapping("/save")public void save() {PrimaryStudent primaryStudent = new PrimaryStudent();SecondaryStudent secondaryStudent = new SecondaryStudent();primaryStudent.setId(1);primaryStudent.setName("mongo");primaryStudent.setSalary(BigDecimal.valueOf(1000));primaryStudent.setBirth(new Date());BeanUtils.copyProperties(primaryStudent, secondaryStudent);studentService.save(primaryStudent, secondaryStudent);}/*** 修改学生** @return 修改结果*/@RequestMapping("/update")public void update() {PrimaryStudent primaryStudent = new PrimaryStudent();SecondaryStudent secondaryStudent = new SecondaryStudent();primaryStudent.setId(1);primaryStudent.setName("mongo");primaryStudent.setSalary(BigDecimal.valueOf(2000));primaryStudent.setBirth(new Date());BeanUtils.copyProperties(primaryStudent, secondaryStudent);studentService.update(primaryStudent, secondaryStudent);}/*** 根据姓名删除学生** @param name 姓名* @return 删除结果*/@RequestMapping("/delete")public void delete(String name) {studentService.delete(name);}/*** 通过名字查找学生** @param name 学生名* @return 学生信息*/@RequestMapping("/find")public void find(String name) {studentService.find(name);}/*** 查找所有学生** @return 学生集合*/@RequestMapping("/all")public void findAll() {studentService.findAll();}}

测试:

http://localhost:8080/student/save

结果:

http://www.lryc.cn/news/179750.html

相关文章:

  • 西门子S7-1200使用LRCF通信库与安川机器人进行EthernetIP通信的具体方法示例
  • pytorch第一天(tensor数据和csv数据的预处理)lm老师版
  • CSP-J第二轮试题-2021年-1.2题
  • 怒刷LeetCode的第16天(Java版)
  • 让大脑自由
  • Arcgis克里金插值报错:ERROR 010079: 无法估算半变异函数。 执行(Kriging)失败。
  • Docker Compose安装
  • 机器人过程自动化(RPA)入门 7. 处理用户事件和助手机器人
  • 在linux下预览markdown的方法,转换成html和pdf
  • AIOT入门指南:探索人工智能与物联网的交汇点
  • CCC数字钥匙设计【NFC】 --车主配对流程介绍
  • 一站式开源持续测试平台 MerterSphere 之测试跟踪操作详解
  • 自然语言处理状况简介
  • python爬虫基于管道持久化存储操作
  • 【MySQL】数据类型(二)
  • 基于Matlab实现连续模型求解方法
  • Tomcat 与 JDK 对应版本关系
  • iOS自动化测试方案(二):Xcode开发者工具构建WDA应用到iphone
  • IDEA的Maven换源
  • 步进电机只响不转
  • 使用select实现服务器并发
  • 【Python】基于OpenCV人脸追踪、手势识别控制的求实之路FPS游戏操作
  • 力扣 -- 718. 最长重复子数组
  • MP、MybatisPlus、联表查询、自定义sql、Constants.WRAPPER、ew (二)
  • Ubuntu服务器安全性提升:修改SSH默认端口号
  • 十七,IBL-打印各个Mipmap级别的hdr环境贴图
  • 7、Docker网络
  • MySQL学习笔记23
  • Java基础---第十篇
  • NLP 03(LSTM)