Springboot双mongodb配置方式
作者:窦再兴
这篇文章主要介绍了Springboot双mongodb配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
准备工作
- 本地mongodb一个
- 创建两个数据库 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:DifficultPassword@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/student repository-package: com.douzi.mongo.dao.primary secondary: uri: mongodb://127.0.0.1:27017/student-two repository-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 @Primary public MongoDbFactory primaryFactory() { if (StringUtils.isEmpty(primaryUri)) { throw new RuntimeException("必须配置mongo primary Uri"); } return new SimpleMongoDbFactory(new MongoClientURI(primaryUri)); } /** * 配置从数据源db工厂 * @param mongo 属性配置信息 * @return 从数据源db工厂 */ @Bean public 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 */ @Id private 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 */ @Id private 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 { @Autowired private PrimaryRepository primaryRepository; @Autowired private 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 { @Autowired private 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
结果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。