Spring Boot实战-集成mongdb并实现自动分库分表

本文介绍了如何在Spring Boot应用中集成MongoDB,并实现自动分库分表的功能。通过添加MongoDB依赖,配置数据库连接信息,创建MongoDBManager读取配置,以及编写Writer和Reader类进行数据操作,实现了MongoDB的CRUD操作。文章强调了MongoDB的文档存储方式和分库分表的实现思路,帮助开发者理解MongoDB在分布式环境中的应用。
摘要由CSDN通过智能技术生成

MongoDB是专为可扩展性,高性能和高可用性而设计的数据库。它可以从单服务器部署扩展到大型、复杂的多数据中心架构。利用内存计算的优势,MongoDB能够提供高性能的数据读写操作。

MongoDB使用文档的方式存储数据,而且非常容易进行分库分表的操作。在Spring Boot中集成mongdb非常简单,只需要在新建项目的时候勾选mongdb一项即可,使用起来也足够简单。但是由于使用时很简单也造成其不够灵活的特点,因此我们需要自己实现一个可以分库分表的mongdb操作代码。

  • 首先在pom.xml中引入mongdb依赖:
         <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
        </dependency>
  • mongdb是一种非关系型数据库,因此使用java连接的话也需要一些身份认证,在application.yml中加入配置信息:
xyh:
  mongodb:
      URI: mongodb://test:test123@127.0.0.1/
      dataBase: comment

注意:以上配置所用到的都是我们自己定义的变量名,127.0.0.1为本机地址,因此需要你额外安装mongdb

  • 有了配置之后就需要用代码去读取这些配置了,新建MongoDBManager.java类用于读取配置信息:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

/**
 * MongoDB管理器
 */
@Component
public class MongoDBManager {
    /**
     * URI
     */
    @Value("${xyh.mongodb.URI}")
    private String uri;
    /**
     * URI
     */
    @Value("${xyh.mongodb.dataBase}")
    private String dataBase;

    /**
     * 获取 MongoClient 对象,可以只创建一个
     *
     * @return MongoClient对象
     */
    @Bean
    public MongoClient mongoClient() {
        System.out.println("\n\n\n\n\n" + uri + dataBase);

        return new MongoClient(new MongoClientURI(uri + dataBase));
    }

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
以下是 Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表实战代码: 1. 添加依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <dependencies> <!-- Sharding-JDBC --> <dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> </dependencies> ``` 2. 配置数据源 在 `application.yml` 文件中配置数据源: ```yaml spring: datasource: # 主库 master: url: jdbc:mysql://localhost:3306/db_master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # 从库 slave: url: jdbc:mysql://localhost:3306/db_slave?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 3. 配置 Sharding-JDBC 在 `application.yml` 文件中配置 Sharding-JDBC: ```yaml spring: shardingsphere: datasource: names: master, slave # 数据源名称 master: type: com.zaxxer.hikari.HikariDataSource slave: type: com.zaxxer.hikari.HikariDataSource config: sharding: tables: user: actualDataNodes: master.user_$->{0..1} # 分表规则,user_0 和 user_1 表 tableStrategy: inline: shardingColumn: id algorithmExpression: user_$->{id % 2} # 分表规则,根据 id 取模 databaseStrategy: inline: shardingColumn: id algorithmExpression: master # 分库规则,根据 id 取模 bindingTables: - user # 绑定表,即需要进行分库分表的表 ``` 4. 配置 Mybatis-Plus 在 `application.yml` 文件中配置 Mybatis-Plus: ```yaml mybatis-plus: configuration: map-underscore-to-camel-case: true # 下划线转驼峰 ``` 5. 编写实体类 创建 `User` 实体类,用于映射数据库中的 `user` 表: ```java @Data public class User { private Long id; private String name; private Integer age; } ``` 6. 编写 Mapper 接口 创建 `UserMapper` 接口,用于定义操作 `user` 表的方法: ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 7. 编写 Service 类 创建 `UserService` 类,用于调用 `UserMapper` 接口中的方法: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getById(Long id) { return userMapper.selectById(id); } public boolean save(User user) { return userMapper.insert(user) > 0; } public boolean updateById(User user) { return userMapper.updateById(user) > 0; } public boolean removeById(Long id) { return userMapper.deleteById(id) > 0; } } ``` 8. 测试 在 `UserController` 类中进行测试: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public User getUser(Long id) { return userService.getById(id); } @PostMapping("/user") public boolean addUser(@RequestBody User user) { return userService.save(user); } @PutMapping("/user") public boolean updateUser(@RequestBody User user) { return userService.updateById(user); } @DeleteMapping("/user") public boolean removeUser(Long id) { return userService.removeById(id); } } ``` 启动应用程序,访问 `http://localhost:8080/user?id=1` 可以得到 `id` 为 1 的用户信息。访问 `http://localhost:8080/user` 并传入用户信息,可以添加用户。访问 `http://localhost:8080/user` 并传入更新后的用户信息,可以更新用户信息。访问 `http://localhost:8080/user?id=1` 并使用 DELETE 方法,可以删除用户。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值