软件编程
位置:首页>> 软件编程>> java编程>> springboot集成@DS注解实现数据源切换的方法示例

springboot集成@DS注解实现数据源切换的方法示例

作者:后台小白鼠  发布时间:2021-11-18 11:30:00 

标签:springboot,@DS注解,数据源切换

启用@DS实现数据源切换

POM内添加核心jar包

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

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: ****

&ldquo;核心&rdquo;-使用@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<Map<String, Object>> selectAll() {
   return  jdbcTemplate.queryForList("select * from user");
 }
 @Override
 @DS("slave_1")
 public List<Map<String, Object>> selectByCondition() {
   return  jdbcTemplate.queryForList("select * from user where age >10");
 }

最后

来源:https://blog.csdn.net/weixin_43975867/article/details/117250634

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com