Springboot雙mongodb配置方式
更新時間:2024年05月29日 14:50:14 作者:竇再興
這篇文章主要介紹了Springboot雙mongodb配置方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
準備工作
- 本地mongodb一個
- 創(chuàng)建兩個數(shù)據(jù)庫 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 關(guān)鍵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多數(shù)據(jù)源配置類 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: 讀取對應(yīng)的配置信息并且構(gòu)造對應(yīng)的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;
/**
* 配置主數(shù)據(jù)源template
* @return 主數(shù)據(jù)源template
*/
@Primary
@Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
public MongoTemplate primaryMongoTemplate() {
return new MongoTemplate(primaryFactory());
}
/**
* 配置從數(shù)據(jù)源template
* @return 從數(shù)據(jù)源template
*/
@Bean
@Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
public MongoTemplate secondaryMongoTemplate() {
return new MongoTemplate(secondaryFactory());
}
/**
* 配置主數(shù)據(jù)源db工廠
* @param mongo 屬性配置信息
* @return 主數(shù)據(jù)源db工廠
*/
@Bean
@Primary
public MongoDbFactory primaryFactory() {
if (StringUtils.isEmpty(primaryUri)) {
throw new RuntimeException("必須配置mongo primary Uri");
}
return new SimpleMongoDbFactory(new MongoClientURI(primaryUri));
}
/**
* 配置從數(shù)據(jù)源db工廠
* @param mongo 屬性配置信息
* @return 從數(shù)據(jù)源db工廠
*/
@Bean
public MongoDbFactory secondaryFactory() {
return new SimpleMongoDbFactory(new MongoClientURI(secondaryUri));
}
}主數(shù)據(jù)源配置 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: 主數(shù)據(jù)源配置
* @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";
}副數(shù)據(jù)源配置 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: 從數(shù)據(jù)源配置
* @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: 主數(shù)據(jù)源學(xué)生對象
* @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: 主數(shù)據(jù)源dao層
* @Date 2023/09/24 16:01
*/
public interface PrimaryRepository extends MongoRepository<PrimaryStudent, Integer> {
/**
* 通過名字查找學(xué)生
*
* @param name 名字
* @return 學(xué)生信息
*/
PrimaryStudent findByName(String name);
/**
* 通過名字刪除學(xué)生
*
* @param name 名字
* @return 學(xué)生信息
*/
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: 副數(shù)據(jù)源學(xué)生對象
* @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: 從數(shù)據(jù)源dao層
* @Date 2023/09/24 16:02
*/
public interface SecondaryRepository extends MongoRepository<SecondaryStudent, Integer> {
/**
* 通過名字查找學(xué)生
*
* @param name 名字
* @return 學(xué)生信息
*/
SecondaryStudent findByName(String name);
/**
* 通過名字刪除學(xué)生
*
* @param name 名字
* @return 學(xué)生信息
*/
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;
/**
* 保存學(xué)生
*
* @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());
}
/**
* 刪除學(xué)生
*
* @param name
* @return
*/
public void delete(String name) {
primaryRepository.deleteById(1);
secondaryRepository.deleteById(1);
}
/**
* 修改學(xué)生
*
* @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());
}
/**
* 查找學(xué)生
*
* @param name 學(xué)生姓名
* @return
*/
public void find(String name) {
PrimaryStudent student1 = primaryRepository.findByName(name);
log.info(student1.toString());
SecondaryStudent student2 = secondaryRepository.findByName(name);
log.info(student2.toString());
}
/**
* 查找學(xué)生集合
*
* @return 學(xué)生集合
*/
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;
/**
* 保存學(xué)生
*
* @return 保存的學(xué)生
*/
@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);
}
/**
* 修改學(xué)生
*
* @return 修改結(jié)果
*/
@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);
}
/**
* 根據(jù)姓名刪除學(xué)生
*
* @param name 姓名
* @return 刪除結(jié)果
*/
@RequestMapping("/delete")
public void delete(String name) {
studentService.delete(name);
}
/**
* 通過名字查找學(xué)生
*
* @param name 學(xué)生名
* @return 學(xué)生信息
*/
@RequestMapping("/find")
public void find(String name) {
studentService.find(name);
}
/**
* 查找所有學(xué)生
*
* @return 學(xué)生集合
*/
@RequestMapping("/all")
public void findAll() {
studentService.findAll();
}
}測試
http://localhost:8080/student/save
結(jié)果



總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決遇到Cannot resolve ch.qos.logback:logback-classic:
當使用Maven配置項目依賴時,可能會遇到無法解析特定版本的錯誤,例如,logback-classic版本1.2.3可能無法在配置的倉庫中找到,解決方法包括檢查倉庫是否包含所需版本,或更新到其他可用版本,可通過Maven官網(wǎng)搜索并找到適用的版本,替換依賴配置中的版本信息2024-09-09
Java基礎(chǔ)知識精通數(shù)組的內(nèi)存分析
數(shù)組對于每一門編程語言來說都是重要的數(shù)據(jù)結(jié)構(gòu)之一,當然不同語言對數(shù)組的實現(xiàn)及處理也不盡相同。Java?語言中提供的數(shù)組是用來存儲固定大小的同類型元素2022-04-04
JavaWeb實戰(zhàn)之開發(fā)網(wǎng)上購物系統(tǒng)(超詳細)
這篇文章主要介紹了JavaWeb實戰(zhàn)之開發(fā)網(wǎng)上購物系統(tǒng)(超詳細),文中有非常詳細的代碼示例,對正在學(xué)習java的小伙伴們有很好的幫助,需要的朋友可以參考下2021-04-04
Spring創(chuàng)建bean對象三種方式代碼實例
這篇文章主要介紹了Spring創(chuàng)建bean對象三種方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下2020-07-07

