第十四篇:Spring Boot+MyBatis配置多数据源

说起多数据源,一般都来用来解决主从模式或者业务比较复杂需要连接不同的分库来支持业务。本篇文章主要讲解后者的模式,利用AOP动态切换来达到项目访问不同数据源。

构架工程

创建一个springboot工程,在其pom文件加入:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.29</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

禁用默认数据源

首先要将Spring Boot自带的DataSourceAutoConfiguration禁用,因为它会读取application.properties文件的spring.datasource.*属性并自动配置单数据源。在@SpringBootApplication注解中添加exclude属性即可

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

配置多数据源连接信息

spring:
  datasource:
    #连接池设置
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 1
    minIdle: 1
    maxIdle: 2
    maxActive: 5
    #主数据源
    ds-main:
      url: jdbc:mysql://localhost:3306/multidb1?&useUnicode=true&characterEncoding=utf-8&useSSL=true
      username: root
      password: root
      driverClassName: com.mysql.jdbc.Driver
    #额外数据源1
    ds-1:
      url: jdbc:mysql://localhost:3306/multidb2?&useUnicode=true&characterEncoding=utf-8&useSSL=true
      username: root
      password: root
      driverClassName: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.chenjie.springboot.learn.entity

创建数据源

由于我们禁掉了自动数据源配置,因些下一步就需要手动将这些数据源创建出来:

@Configuration
public class DataSourceConfig {
    //数据源1
    @Bean(name = "datasource1")
    @ConfigurationProperties(prefix = "spring.datasource.ds-main") // application.properteis中对应属性的前缀
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    //数据源2
    @Bean(name = "datasource2")
    @ConfigurationProperties(prefix = "spring.datasource.ds-1") // application.properteis中对应属性的前缀
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }
}

动态数据源

使用动态数据源的初衷,是能在应用层做到读写分离,即在程序代码中控制不同的查询方法去连接不同的库。除了这种方法以外,数据库中间件也是个不错的选择,它的优点是数据库集群对应用来说只暴露为单库,不需要切换数据源的代码逻辑。我们通过自定义注解 + AOP的方式实现数据源动态切换。首先定义一个DataSourceContextHolder , 用于保存当前线程使用的数据源名:

public class DataSourceContextHolder {
    private static final Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);
    /**
     * 默认数据源
     */
    public static final String DEFAULT_DS = "datasource1";

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    // 设置数据源名
    public static void setDB(String dbType) {
        logger.info("切换到{"+dbType+"}数据源");
        contextHolder.set(dbType);
    }

    // 获取数据源名
    public static String getDB() {
        return (contextHolder.get());
    }

    // 清除数据源名
    public static void clearDB() {
        contextHolder.remove();
    }
}

然后自定义一个javax.sql.DataSource接口的实现,这里只需要继承Spring为我们预先实现好的父类AbstractRoutingDataSource即可:

public class DynamicDataSource extends AbstractRoutingDataSource {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    protected Object determineCurrentLookupKey() {
        logger.info("数据源为"+DataSourceContextHolder.getDB());
        return DataSourceContextHolder.getDB();
    }
}

创建动态数据源:
在DataSourceConfig 中添加如下代码

/**
* 动态数据源: 通过AOP在不同数据源之间动态切换
* @return
*/
@Primary
@Bean(name = "dynamicDataSource")
public DataSource dynamicDataSource() {
   DynamicDataSource dynamicDataSource = new DynamicDataSource();
   // 默认数据源
   dynamicDataSource.setDefaultTargetDataSource(dataSource1());
   // 配置多数据源
   Map<Object, Object> dsMap = new HashMap();
   dsMap.put("datasource1", dataSource1());
   dsMap.put("datasource2", dataSource2());

   dynamicDataSource.setTargetDataSources(dsMap);
   return dynamicDataSource;
}

/**
* 配置@Transactional注解事物
* @return
*/
@Bean
public PlatformTransactionManager transactionManager() {
   return new DataSourceTransactionManager(dynamicDataSource());
}

自定义注释@DS用于在编码时指定方法使用哪个数据源:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface DS {
    String value() default "datasource1";
}

编写AOP切面,实现切换逻辑:

@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(DS)")
    public void beforeSwitchDS(JoinPoint point){
        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();
        //获得访问的方法名
        String methodName = point.getSignature().getName();
        //得到方法的参数的类型
        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        try {
            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);
            // 判断是否存在@DS注解
            if (method.isAnnotationPresent(DS.class)) {
                DS annotation = method.getAnnotation(DS.class);
                // 取出注解中的数据源名
                dataSource = annotation.value();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);
    }

    @After("@annotation(DS)")
    public void afterSwitchDS(JoinPoint point){
        DataSourceContextHolder.clearDB();
    }
}

完成上述配置后,在先前SqlSessionFactory配置中指定使用DynamicDataSource就可以在Service中愉快的切换数据源了。

Service

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    //使用数据源1查询
    @DS("datasource1")
    public List<User> findUserList1(){
        return userMapper.findUserList();
    }
    //使用数据源2查询
    @DS("datasource2")
    public List<User> findUserList2(){
        return userMapper.findUserList();
    }


    @DS("datasource1")
    public User findUser1(int id) {
        return userMapper.findUser(id);
    }
    @DS("datasource2")
    public User findUser2(int id){
        return userMapper.findUser(id);
    }

    @DS("datasource1")
    public int add1(User user){
        return userMapper.add(user);
    }
    @DS("datasource2")
    public int add2(User user){
       return userMapper.add(user);
    }
    @DS("datasource1")
    public int delete1(int id){
        return userMapper.delete(id);
    }
    @DS("datasource2")
    public int delete2(int id){
        return userMapper.delete(id);
    }
    @DS("datasource1")
    public int update1(User user){
        return userMapper.update(user);
    }
    @DS("datasource2")
    public int update2(User user){
        return userMapper.update(user);
    }
}

Controller

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/list")
    public List<User> findUserList() {
        return userService.findUserList1();
    }

    @GetMapping(value = "/{id}")
    public User findUser(@PathVariable("id") int id) {
        return userService.findUser1(id);
    }

    @PutMapping(value = "/{id}")
    public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
                                @RequestParam(value = "age", required = true) int age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        if (0 < userService.update1(user)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @DeleteMapping(value = "/{id}")
    public String delete(@PathVariable(value = "id") int id) {
        if (0 < userService.delete1(id)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @PostMapping(value = "/add")
    public String postAccount(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
                              @RequestParam(value = "age") int age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        if (0 < userService.add1(user)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @GetMapping(value = "/db2/list")
    public List<User> findUserList2() {
        return userService.findUserList2();
    }

    @GetMapping(value = "/db2/{id}")
    public User findUser2(@PathVariable("id") int id) {
        return userService.findUser2(id);
    }

    @PutMapping(value = "/db2/{id}")
    public String updateAccount2(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
                                @RequestParam(value = "age", required = true) int age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        if (0 < userService.update2(user)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @DeleteMapping(value = "/db2/{id}")
    public String delete2(@PathVariable(value = "id") int id) {
        if (0 < userService.delete2(id)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @PostMapping(value = "/db2/add")
    public String postAccount2(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
                              @RequestParam(value = "age") int age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        if (0 < userService.add2(user)) {
            return "success";
        } else {
            return "fail";
        }
    }
}

测试

在这里插入图片描述
数据源切换成功

源码下载:https://github.com/chenjary/SpringBoot

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值