关注「Raymond运维」公众号,并设为「星标」,第一时间获取更多运维等文章,不再错过精彩内容。
目录
1. Spring Boot 项目整合 MongoDB 可以通过以下步骤完成:
2、对 MongoDB 进行分片或复制集操作

1. Spring Boot 项目整合 MongoDB 可以通过以下步骤完成:
添加依赖
在项目的 pom.xml 文件中添加 MongoDB 驱动和 Spring Data MongoDB 的依赖,如下:
<dependencies><!-- MongoDB 驱动 --><dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver-sync</artifactId><version>4.4.0</version></dependency><!-- Spring Data MongoDB --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId><version>2.6.2</version></dependency></dependencies>
配置 MongoDB 连接
在 application.properties 文件中配置 MongoDB 的连接信息,如下:
spring.data.mongodb.uri=mongodb://username:password@localhost:27017/myDatabase
创建实体类
创建一个实体类,并使用注解来定义文档结构和映射关系。例如:
import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;@Document(collection = "users")public class User {@Idprivate String id;private String name;private int age;// Getters and setters}
创建 Repository 接口
创建一个继承自 JpaRepository 的接口,并为其添加方法。例如:
import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository;@Repositorypublic interface UserRepository extends CrudRepository<User, String> {}
在 Service 层使用 Repository
在 Service 层,注入 UserRepository 并使用它来进行 CRUD 操作。例如:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class UserService {@Autowiredprivate UserRepository userRepository;public User save(User user) {return userRepository.save(user);}public User findById(String id) {return userRepository.findById(id).orElse(null);}// 其他 CRUD 方法}
在 Controller 层处理 HTTP 请求
在 Controller 层,注入 UserService 并处理 HTTP 请求。例如:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/users")public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic User save(@RequestBody User user) {return userService.save(user);}@GetMapping("/{id}")public User findById(@PathVariable String id) {return userService.findById(id);}}
注意事项:
请确保 MongoDB 服务已经启动并正确配置。
实体类中的属性要与 MongoDB 数据库中的字段对应。
如果需要对 MongoDB 进行分片或者复制集操作,请参考 Spring Data MongoDB 的官方文档。
通过以上步骤,一个简单的 Spring Boot 项目就完成了与 MongoDB 的整合。在实际项目中,还可以根据需求添加更多的配置和操作方法。

2、对 MongoDB 进行分片或复制集操作
在 Spring Boot 项目中,对 MongoDB 进行分片或复制集操作,主要依赖 spring-data-mongodb 库提供的扩展点。
分片(Sharding):
分片是将数据库的集合(Collection)分散在多个数据库服务器上,以提高查询性能和扩展性。在 Spring Boot 项目中,可以通过以下方式对 MongoDB 进行分片操作:
在application.properties或application.yml中配置分片信息,例如:
spring.data.mongodb.shard-strategy=org.springframework.data.mongodb.core.shard.BackwardCompatibleShardingStrategyspring.data.mongodb.target-db-config.default.mongo-uri=mongodb://localhost:27017/mydbspring.data.mongodb.target-db-config.default.database=mydbspring.data.mongodb.target-db-config.shard-targets={\"ds\"=>0,\"target\"=>\"mydb_${0..199}\"}
创建一个@Configuration类,用于配置分片策略和数据库实例:
@Configurationpublic class MongoDBConfiguration {@Beanpublic ShardingDataSource shardingDataSource() {// 创建一个分片数据源// ...}@Beanpublic MongoDatabaseFactory mongoDatabaseFactory() {// 创建一个 MongoDatabaseFactory 实例// ...}}
在需要进行分片操作的地方,使用@MongoRepository或@MongoUnitOfWork注解:
@Servicepublic class MyService {@MongoRepositorypublic MyCollectionRepository myCollectionRepository() {// 创建一个分片集合的仓库// ...}}
复制集(Replica Set):
复制集是由多个 MongoDB 实例组成的集合,可以提供数据备份和读写分离。在 Spring Boot 项目中,可以通过以下方式对 MongoDB 进行复制集操作:
在application.properties或application.yml中配置复制集信息,例如:
spring.data.mongodb.replica-set=myReplicaSetspring.data.mongodb.host=mongodb://localhost:27017spring.data.mongodb.port=27017spring.data.mongodb.authentication-database=adminspring.data.mongodb.database=mydb
创建一个@Configuration类,用于配置复制集实例:
@Configurationpublic class MongoDBConfiguration {@Beanpublic MongoClient mongoClient() {// 创建一个 MongoClient 实例// ...}}
在需要进行复制集操作的地方,使用@MongoRepository或@MongoUnitOfWork注解:
@Servicepublic class MyService {@MongoRepositorypublic MyCollectionRepository myCollectionRepository() {// 创建一个复制集集合的仓库// ...}}
需要注意的是,以上操作均需要引入 spring-data-mongodb 依赖。在 pom.xml 中添加以下依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
并且确保 JDK 版本高于 1.8,以支持分片和复制集功能。
链接:https://python-basketball.blog.csdn.net/article/details/133876441?spm=1001.2014.3001.5502
(版权归原作者所有,侵删)
微
信
群
WeChat group

为方便大家更好的交流运维等相关技术问题,特创建了微信交流群。需要加群的小伙伴们在关注微信公众号后,点击底部菜单关于→联系我,即可获取加群方式。
博客
客
Blog


CSDN博客

掘金博客
长按识别二维码访问博客网站,查看更多优质原创运维等文章。




