一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

springboot集成@DS注解实现数据源切换代码方法

时间:2022-03-09 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下springboot集成@DS注解实现数据源切换代码方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

启用@DS实现数据源切换

POM内添加核心jar包

        
            com.baomidou
            dynamic-datasource-spring-boot-starter
            3.0.0
        

yml配置

spring:
  datasource:
    #配置hikari连接池
    hikari:
      minimum-idle: 4
      maximum-pool-size: 16
      connection-timeout: 10000
      idle-timeout: 30000
      connection-init-sql: set names utf8mb4
    #动态数据源配置
    dynamic:
      #主数据源,默认启用
      primary: business
      datasource:
        #数据源1
        business:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/db_business?useUnicode=true&characterEncoding=utf-8
          username: ****
          password: ****
        #数据源2
        user:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/db_user?useUnicode=true&characterEncoding=utf-8
          username: ****
          password: ****
        #数据源3
        order:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/db_order?useUnicode=true&characterEncoding=utf-8
          username: ****
          password: ****

“核心”-使用@DS注解

使用@DS注解的核心是什么呢?

1.注解添加在dao.mapper上无效

2.注解添加到interface Service类上无效

3.注解添加到interface Service方法上无效

那么,此注解应该如何使用呢?

添加@DS注解到实现类或者实现类的方法上才可以

当注解添加到类上,意味着此类里的方法都使用此数据源;

当注解添加到方法上时,意味着此方法上使用的数据源优先级高于其他一切配置

@Service
@DS("slave")
public class UserServiceImpl implements UserService {
 
  @Autowired
  private JdbcTemplate jdbcTemplate;
 
  public List> selectAll() {
    return  jdbcTemplate.queryForList("select * from user");
  }
  @Override
  @DS("slave_1")
  public List> selectByCondition() {
    return  jdbcTemplate.queryForList("select * from user where age >10");
  }

热门栏目