SpringCloud集成MybatisPlus,实现MySQL多数据源配置

引入依赖

html 复制代码
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.15</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

配置多数据源

在application.properties中配置多数据源:

text 复制代码
spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.master.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
spring.datasource.master.username=root
spring.datasource.master.password=root

spring.datasource.slave.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.slave.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
spring.datasource.slave.username=root
spring.datasource.slave.password=root

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.pool.init-size=10
spring.datasource.pool.max-size=20
spring.datasource.pool.min-size=5
spring.datasource.pool.max-wait=30000
spring.datasource.filters=stat,wall,log4j
spring.datasource.log-enabled=true
spring.datasource.log-prefix=druid.log
spring.datasource.stat-view-servlet.enabled=true
spring.datasource.stat-view-servlet.url-pattern=/druid/*
spring.datasource.web-stat-filter.enabled=true
spring.datasource.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
spring.datasource.max-total=20
spring.datasource.max-idle=10
spring.datasource.min-idle=5
spring.datasource.time-between-eviction-runs-millis=60000
spring.datasource.min-evictable-idle-time-millis=300000
spring.datasource.validation-query=SELECT 1 FROM dual
spring.datasource.test-on-borrow=true
spring.datasource.test-on-return=true
spring.datasource.test-while-idle=true
spring.datasource.remove-abandoned=true
spring.datasource.remove-abandoned-timeout=60000
spring.datasource.log-abandoned=true

配置解释

这是一个Spring Boot应用程序中用于配置数据库连接的属性文件。以下是每个配置项目的解释:

  1. spring.datasource.master.driver-class-name: 指定主数据库的JDBC驱动程序类名,这里是MySQL数据库的驱动类。
  2. spring.datasource.master.url: 主数据库的JDBC URL,指定了数据库的位置和连接参数,包括字符编码、时区等。
  3. spring.datasource.master.username: 主数据库的用户名。
  4. spring.datasource.master.password: 主数据库的密码。
  5. spring.datasource.slave.driver-class-name: 指定从数据库(副本)的JDBC驱动程序类名,同样是MySQL数据库的驱动类。
  6. spring.datasource.slave.url: 从数据库的JDBC URL,与主数据库不同的地方可能包括不同的数据库名称或连接参数。
  7. spring.datasource.slave.username: 从数据库的用户名。
  8. spring.datasource.slave.password: 从数据库的密码。
  9. spring.datasource.type: 数据源类型,这里使用了阿里巴巴的Druid数据源。
  10. spring.datasource.pool.init-size: 数据源的初始连接池大小,表示在启动时会创建的数据库连接数。
  11. spring.datasource.pool.max-size: 数据源的最大连接池大小,表示连接池中允许存在的最大连接数。
  12. spring.datasource.pool.min-size: 数据源的最小连接池大小,表示连接池中允许存在的最小连接数。
  13. spring.datasource.pool.max-wait: 获取连接时的最大等待时间(毫秒),如果连接池中的连接都被占用,且达到最大连接数,新请求会等待一段时间。
  14. spring.datasource.filters: 数据源的过滤器,可以用于监控、安全等目的。这里包括了统计(stat)、SQL防火墙(wall)和日志(log4j)。
  15. spring.datasource.log-enabled: 是否启用Druid的连接池日志。
  16. spring.datasource.log-prefix: 连接池日志的前缀。
  17. spring.datasource.stat-view-servlet.enabled: 是否启用Druid的统计数据查看servlet。
  18. spring.datasource.stat-view-servlet.url-pattern: 统计数据查看servlet的URL路径。
  19. spring.datasource.web-stat-filter.enabled: 是否启用Druid的Web统计过滤器。
  20. spring.datasource.web-stat-filter.exclusions: 需要排除统计的资源路径,如JavaScript、图片等。
  21. spring.datasource.max-total: 最大活动连接数,与spring.datasource.pool.max-size相同。
  22. spring.datasource.max-idle: 最大空闲连接数。
  23. spring.datasource.min-idle: 最小空闲连接数。
  24. spring.datasource.time-between-eviction-runs-millis: 连接池定期检查空闲连接的时间间隔。
  25. spring.datasource.min-evictable-idle-time-millis: 连接池中连接的最小空闲时间,超过此时间的连接将被回收。
  26. spring.datasource.validation-query: 用于验证连接是否有效的SQL查询。
  27. spring.datasource.test-on-borrow: 是否在借用连接时测试连接的有效性。
  28. spring.datasource.test-on-return: 是否在归还连接时测试连接的有效性。
  29. spring.datasource.test-while-idle: 是否在连接空闲时测试连接的有效性。
  30. spring.datasource.remove-abandoned: 是否移除长时间未使用的连接。
  31. spring.datasource.remove-abandoned-timeout: 设置长时间未使用连接的超时时间。
  32. spring.datasource.log-abandoned: 是否记录移除连接的日志。
    这些配置项用于定义应用程序与数据库之间的连接池、数据库连接属性和连接池监控等相关设置。不同的配置项可以根据应用程序的需求进行调整。

配置MybatisPlus

在application.properties中配置MybatisPlus:

text 复制代码
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.global-config.id-type=auto
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
mybatis-plus.global-config.base-namespace=test
mybatis-plus.global-config.mapper-namespace=test.mapper

配置MybatisPlus解释

这是一个MyBatis Plus(通常简称为MyBatis+或MP)的配置文件,用于配置MyBatis Plus在Spring Boot应用程序中的行为。以下是每个配置项目的解释:

  1. mybatis-plus.mapper-locations=classpath:mapper/*.xml: 这个配置项指定了MyBatis Plus的Mapper XML文件的位置。在这个例子中,它告诉MyBatis Plus在类路径下的"mapper"目录中查找所有以".xml"结尾的文件,以作为Mapper定义文件。
  2. mybatis-plus.global-config.id-type=auto: 这个配置项指定了主键ID的生成策略。在这里,设置为"auto"表示使用数据库自动生成的主键值,这通常是由数据库管理的自增长或唯一标识符。
  3. mybatis-plus.global-config.db-config.logic-delete-value=1: 这个配置项指定了逻辑删除的值。在MyBatis Plus中,逻辑删除是一种通过标记记录来表示删除状态的方式,这里设置为"1"表示已删除。
  4. mybatis-plus.global-config.db-config.logic-not-delete-value=0: 这个配置项指定了逻辑未删除的值。在MyBatis Plus中,这是指记录未被删除的状态,这里设置为"0"表示未删除。
  5. mybatis-plus.global-config.base-namespace=test: 这个配置项指定了基础的Mapper命名空间。这个命名空间将会被用于生成Mapper接口的全限定名,通常与包名相关联。
  6. mybatis-plus.global-config.mapper-namespace=test.mapper: 这个配置项指定了Mapper接口的命名空间。在MyBatis Plus中,Mapper接口与XML文件相关联,这个配置项将会在生成的Mapper接口中设置XML文件的命名空间。
    这些配置项用于自定义MyBatis Plus的行为,包括主键生成策略、逻辑删除的值、Mapper接口命名空间等。它们允许根据应用程序的需求来配置和控制MyBatis Plus的行为。

配置Mapper

创建一个Mapper接口,例如UserMapper:

java 复制代码
@Mapper
public interface UserMapper extends BaseMapper<User> {
}

使用多数据源

在需要使用多数据源的地方,使用@MapperScan注解指定Mapper所在包路径:

javascript 复制代码
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @MapperScan("com.example.demo.mapper")
    public class MyApp {
        // ...
    }
}

CRUD示例

javascript 复制代码
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User save(User user) {
        return userMapper.save(user);
    }

    @Override
    public User update(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteById(id);
    }
}
javascript 复制代码
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public User save(@RequestBody User user) {
        return userService.save(user);
    }

    @PutMapping("/{id}")
    public User update(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return userService.update(user);
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        userService.delete(id);
    }
}

使用不同数据源

要使用不同的数据源查询,可以在Mapper接口中使用@MapperScan注解指定需要使用的数据源,例如:

javascript 复制代码
@MapperScan("com.example.demo.mapper.master")
public interface UserMapperMaster extends BaseMapper<User> {
}

@MapperScan("com.example.demo.mapper.slave")
public interface UserMapperSlave extends BaseMapper<User> {
}

然后在需要使用不同数据源的地方,使用@Autowired注解注入对应的Mapper接口,例如:

javascript 复制代码
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapperMaster userMapperMaster;

    @Autowired
    private UserMapperSlave userMapperSlave;

    @Override
    public User save(User user) {
        return userMapperMaster.save(user);
    }

    @Override
    public User update(User user) {
        return userMapperMaster.updateById(user);
    }

    @Override
    public User findById(Long id) {
        return userMapperMaster.selectById(id);
    }

    @Override
    public void delete(Long id) {
        userMapperMaster.deleteById(id);
    }
}

要在某个方法上使用不同的数据源,可以在该方法上使用@MapperScan注解指定需要使用的数据源,例如:

javascript 复制代码
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapperMaster userMapperMaster;

    @Autowired
    private UserMapperSlave userMapperSlave;

    @Override
    public User save(User user) {
        return userMapperMaster.save(user);
    }

    @Override
    public User update(User user) {
        return userMapperMaster.updateById(user);
    }

    @Override
    public User findById(Long id) {
        return userMapperMaster.selectById(id);
    }

    @Override
    public void delete(Long id) {
        userMapperMaster.deleteById(id);
    }

    @MapperScan("com.example.demo.mapper.slave")
    @Override
    public User findByIdSlave(Long id) {
        return userMapperSlave.selectById(id);
    }
}
相关推荐
小菜yh1 小时前
关于Redis
java·数据库·spring boot·redis·spring·缓存
爱上语文2 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
荆州克莱2 小时前
springcloud整合nacos、sentinal、springcloud-gateway,springboot security、oauth2总结
spring boot·spring·spring cloud·css3·技术
这孩子叫逆8 小时前
6. 什么是MySQL的事务?如何在Java中使用Connection接口管理事务?
数据库·mysql
拾光师9 小时前
spring获取当前request
java·后端·spring
xujinwei_gingko10 小时前
Spring IOC容器Bean对象管理-Java Config方式
java·spring
掘根10 小时前
【网络】高级IO——poll版本TCP服务器
网络·数据库·sql·网络协议·tcp/ip·mysql·网络安全
Bear on Toilet11 小时前
初写MySQL四张表:(3/4)
数据库·mysql
无妄啊______11 小时前
mysql笔记9(子查询)
数据库·笔记·mysql
Xua305511 小时前
浅谈Spring Cloud:认识微服务
spring·spring cloud·微服务