好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解Spring Boot + Mybatis 实现动态数据源

动态数据源

在很多具体应用场景的时候,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库。又比如业务a要访问a数据库,业务b要访问b数据库等,都可以使用动态数据源方案进行解决。接下来,我们就来讲解如何实现动态数据源,以及在过程中剖析动态数据源背后的实现原理。

实现案例

本教程案例基于 spring boot + mybatis + mysql 实现。

数据库设计

首先需要安装好mysql数据库,新建数据库 example,创建example表,用来测试数据源,sql脚本如下:

?

1

2

3

4

5

6

7

create table `example` (

  `pk` bigint( 20 ) unsigned not null auto_increment comment '主键' ,

  `message` varchar( 100 ) not null ,

  `create_time` datetime not null comment '创建时间' ,

  `modify_time` datetime default null comment '生效时间' ,

  primary key (`pk`)

) engine=innodb auto_increment= 2 default charset=utf8 row_format=compact comment= '测试用例表'

添加依赖

添加spring boot,spring aop,mybatis,mysql相关依赖。

pom.xml

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<dependency>

    <groupid>org.springframework.boot</groupid>

    <artifactid>spring-boot-starter-web</artifactid>

   </dependency>

   <dependency>

    <groupid>org.springframework.boot</groupid>

    <artifactid>spring-boot-starter-test</artifactid>

    <scope>test</scope>

   </dependency>

   <dependency>

    <groupid>org.mybatis.spring.boot</groupid>

    <artifactid>mybatis-spring-boot-starter</artifactid>

    <version> 1.3 . 1 </version>

   </dependency>

   <!-- spring aop -->

   <dependency>

    <groupid>org.springframework.boot</groupid>

    <artifactid>spring-boot-starter-aop</artifactid>

   </dependency>

   <dependency>

    <groupid>mysql</groupid>

    <artifactid>mysql-connector-java</artifactid>

    <version> 5.1 . 8 </version>

   </dependency>

自定义配置文件

新建自定义配置文件resource/config/mysql/db.properties,添加数据源:

?

1

2

3

4

5

#数据库设置

spring.datasource.example.jdbc-url=jdbc:mysql: //localhost:3306/example?characterencoding=utf-8

spring.datasource.example.username=root

spring.datasource.example.password= 123456

spring.datasource.example.driver- class -name=com.mysql.jdbc.driver

启动类

启动类添加 exclude = {datasourceautoconfiguration.class}, 以禁用数据源默认自动配置。

数据源默认自动配置会读取 spring.datasource.* 的属性创建数据源,所以要禁用以进行定制。

dynamicdatasourceapplication.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.main.example.dynamic.datasource;

 

import org.springframework.boot.springapplication;

import org.springframework.boot.autoconfigure.springbootapplication;

import org.springframework.boot.autoconfigure.jdbc.datasourceautoconfiguration;

 

@springbootapplication (exclude = {

     datasourceautoconfiguration. class

})

public class dynamicdatasourceapplication {

 

  public static void main(string[] args) {

   springapplication.run(dynamicdatasourceapplication. class , args);

  }

 

}

数据源配置类

创建一个数据源配置类,主要做以下几件事情:

1. 配置 dao,model(bean),xml mapper文件的扫描路径。

2. 注入数据源配置属性,创建数据源。

3. 创建一个动态数据源,装入数据源。

4. 将动态数据源设置到sql会话工厂和事务管理器。

如此,当进行数据库操作时,就会通过我们创建的动态数据源去获取要操作的数据源了。

dbsourceconfig.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

package com.main.example.config.dao;

 

import com.main.example测试数据mon.dataenum;

import com.main.example测试数据mon.dynamicdatasource;

import org.mybatis.spring.sqlsessionfactorybean;

import org.springframework.boot.context.properties.configurationproperties;

import org.springframework.boot.jdbc.datasourcebuilder;

import org.springframework.context.annotation.bean;

import org.springframework.context.annotation.configuration;

import org.springframework.context.annotation.propertysource;

import org.springframework.core.io.support.pathmatchingresourcepatternresolver;

import org.springframework.jdbc.datasource.datasourcetransactionmanager;

import org.springframework.transaction.platformtransactionmanager;

 

import javax.sql.datasource;

import java.util.hashmap;

import java.util.map;

 

//数据库配置统一在config/mysql/db.properties中

@configuration

@propertysource (value = "classpath:config/mysql/db.properties" )

public class dbsourceconfig {

   private string typealiasespackage = "com.main.example.bean.**.*" ;

 

   @bean (name = "exampledatasource" )

   @configurationproperties (prefix = "spring.datasource.example" )

   public datasource exampledatasource() {

     return datasourcebuilder.create().build();

   }

 

   /*

    * 动态数据源

    * dbmap中存放数据源名称与数据源实例,数据源名称存于dataenum.dbsource中

    * setdefaulttargetdatasource方法设置默认数据源

    */

   @bean(name = "dynamicdatasource")

   public datasource dynamicdatasource() {

     dynamicdatasource dynamicdatasource = new dynamicdatasource();

     //配置多数据源

     map<object, object> dbmap = new hashmap();

     dbmap.put(dataenum.dbsource.example.getname(), exampledatasource());

     dynamicdatasource.settargetdatasources(dbmap);

 

     // 设置默认数据源

     dynamicdatasource.setdefaulttargetdatasource(exampledatasource());

 

     return dynamicdatasource;

   }

 

   /*

    * 数据库连接会话工厂

    * 将动态数据源赋给工厂

    * mapper存于resources/mapper目录下

    * 默认bean存于com.main.example.bean包或子包下,也可直接在mapper中指定

    */

   @bean (name = "sqlsessionfactory" )

   public sqlsessionfactorybean sqlsessionfactory() throws exception {

     sqlsessionfactorybean sqlsessionfactory = new sqlsessionfactorybean();

     sqlsessionfactory.setdatasource(dynamicdatasource());

     sqlsessionfactory.settypealiasespackage(typealiasespackage); //扫描bean

     pathmatchingresourcepatternresolver resolver = new pathmatchingresourcepatternresolver();

     sqlsessionfactory.setmapperlocations(resolver.getresources( "classpath*:mapper/*.xml" ));  // 扫描映射文件

 

     return sqlsessionfactory;

   }

 

   @bean

   public platformtransactionmanager transactionmanager() {

     // 配置事务管理, 使用事务时在方法头部添加@transactional注解即可

     return new datasourcetransactionmanager(dynamicdatasource());

   }

}

动态数据源类

我们上一步把这个动态数据源设置到了sql会话工厂和事务管理器,这样在操作数据库时就会通过动态数据源类来获取要操作的数据源了。

动态数据源类集成了spring提供的abstractroutingdatasource类,abstractroutingdatasource 中获取数据源的方法就是 determinetargetdatasource,而此方法又通过 determinecurrentlookupkey 方法获取查询数据源的key。

所以如果我们需要动态切换数据源,就可以通过以下两种方式定制:

1. 覆写 determinecurrentlookupkey 方法

通过覆写 determinecurrentlookupkey 方法,从一个自定义的 dbsourcecontext.getdbsource() 获取数据源key值,这样在我们想动态切换数据源的时候,只要通过  dbsourcecontext.setdbsource(key)  的方式就可以动态改变数据源了。这种方式要求在获取数据源之前,要先初始化各个数据源到 dbsourcecontext 中,我们案例就是采用这种方式实现的,所以要将数据源都事先初始化到dynamicdatasource 中。

2. 可以通过覆写 determinetargetdatasource,因为数据源就是在这个方法创建并返回的,所以这种方式就比较自由了,支持到任何你希望的地方读取数据源信息,只要最终返回一个 datasource 的实现类即可。比如你可以到数据库、本地文件、网络接口等方式读取到数据源信息然后返回相应的数据源对象就可以了。

dynamicdatasource.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

package com.main.example测试数据mon;

 

import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource;

 

public class dynamicdatasource extends abstractroutingdatasource {

 

   @override

   protected object determinecurrentlookupkey() {

     return dbsourcecontext.getdbsource();

   }

 

}

数据源上下文

动态数据源的切换主要是通过调用这个类的方法来完成的。在任何想要进行切换数据源的时候都可以通过调用这个类的方法实现切换。比如系统登录时,根据用户信息调用这个类的数据源切换方法切换到用户对应的数据库。完整代码如下:

dbsourcecontext.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package com.main.example测试数据mon;

 

import org.apache.log4j.logger;

 

public class dbsourcecontext {

   private static logger logger = logger.getlogger(dbsourcecontext. class );

 

   private static final threadlocal<string> dbcontext = new threadlocal<string>();

 

   public static void setdbsource(string source) {

     logger.debug( "set source ====>" + source);

     dbcontext.set(source);

   }

 

   public static string getdbsource() {

     logger.debug( "get source ====>" + dbcontext.get());

     return dbcontext.get();

   }

 

   public static void cleardbsource() {

     dbcontext.remove();

   }

}

注解式数据源

到这里,在任何想要动态切换数据源的时候,只要调用dbsourcecontext.setdbsource(key)  就可以完成了。

接下来我们实现通过注解的方式来进行数据源的切换,原理就是添加注解(如@dbsource(value="example")),然后实现注解切面进行数据源切换。

创建一个动态数据源注解,拥有一个value值,用于标识要切换的数据源的key。

dbsource.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

package com.main.example.config.dao;

 

import java.lang.annotation.*;

 

/**

  * 动态数据源注解

  * @author

  * @date april 12, 2019

  */

@target ({elementtype.method, elementtype.type})

@retention (retentionpolicy.runtime)

@documented

public @interface dbsource {

   /**

    * 数据源key值

    * @return

    */

   string value();

}

创建一个aop切面,拦截带 @datasource 注解的方法,在方法执行前切换至目标数据源,执行完成后恢复到默认数据源。

dynamicdatasourceaspect.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

package com.main.example.config.dao;

 

import com.main.example测试数据mon.dbsourcecontext;

import org.apache.log4j.logger;

import org.aspectj.lang.joinpoint;

import org.aspectj.lang.annotation.after;

import org.aspectj.lang.annotation.aspect;

import org.aspectj.lang.annotation.before;

import org.springframework.core.annotation.order;

import org.springframework.stereotype测试数据ponent;

 

/**

  * 动态数据源切换处理器

  * @author linzhibao

  * @date april 12, 2019

  */

@aspect

@order (- 1 ) // 该切面应当先于 @transactional 执行

@component

public class dynamicdatasourceaspect {

   private static logger logger = logger.getlogger(dynamicdatasourceaspect. class );

   /**

    * 切换数据源

    * @param point

    * @param dbsource

    */

   //@before("@annotation(dbsource)") 注解在对应方法,拦截有@dbsource的方法

   //注解在类对象,拦截有@dbsource类下所有的方法

   @before ( "@within(dbsource)" )

   public void switchdatasource(joinpoint point, dbsource dbsource) {

       // 切换数据源

       dbsourcecontext.setdbsource(dbsource.value());

   }

 

   /**

    * 重置数据源

    * @param point

    * @param dbsource

    */

   //注解在类对象,拦截有@dbsource类下所有的方法

   @after ( "@within(dbsource)" )

   public void restoredatasource(joinpoint point, dbsource dbsource) {

     // 将数据源置为默认数据源

     dbsourcecontext.cleardbsource();

   }

}

到这里,动态数据源相关的处理代码就完成了。

编写用户业务代码

接下来编写用户查询业务代码,用来进行测试,dao层只需添加一个查询接口即可。

exampledao.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package com.main.example.dao;

 

import com.main.example测试数据mon.dataenum;

import com.main.example.config.dao.dbsource;

import org.springframework.context.annotation.bean;

import org.springframework.stereotype测试数据ponent;

 

import javax.annotation.resource;

import java.util.list;

 

@component ( "exampledao" )

//切换数据源注解,以dataenum.dbsource中的值为准

@dbsource ( "example" )

public class exampledao extends daobase {

   private static final string mapper_name_space = "com.main.example.dao.examplemapper" ;

 

   public list<string> selectallmessages() {

     return selectlist(mapper_name_space, "selectallmessages" );

   }

}

controler代码:

testexampledao.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

package com.main.example.dao;

 

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.web.bind.annotation.requestmapping;

import org.springframework.web.bind.annotation.restcontroller;

 

import java.util.arraylist;

import java.util.list;

 

@restcontroller

public class testexampledao {

   @autowired

   exampledao exampledao;

 

   @requestmapping (value = "/test/example" )

   public list<string> selectallmessages() {

     try {

       list<string> ldata = exampledao.selectallmessages();

       if (ldata == null ){system.out.println( "*********it is null.***********" ); return null ;}

       for (string d : ldata) {

         system.out.println(d);

       }

       return ldata;

     } catch (exception e) {

       e.printstacktrace();

     }

 

     return new arraylist<>();

   }

}

examplemapper.xml代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

<?xml version= "1.0" encoding= "utf-8" ?>

<!doctype mapper

     public "-//mybatis.org//dtd mapper 3.0//en"

     "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace= "com.main.example.dao.examplemapper" >

   <select id= "selectallmessages" resulttype= "java.lang.string" >

     select

     message

     from example

   </select>

 

</mapper>

测试效果

启动系统,访问 http://localhost:80/test/example">http://localhost:80/test/example,分别测试两个接口,成功返回数据。

 

可能遇到的问题

1.报错:java.lang.illegalargumentexception: jdbcurl is required with driverclassname

 

原因:

spring boot从1.x升级到2.x版本之后,一些配置及用法有了变化,如果不小心就会碰到[jdbcurl is required with driverclassname.]的错误

解决方法:

在1.0 配置数据源的过程中主要是写成:spring.datasource.url 和spring.datasource.driverclassname。

而在2.0升级之后需要变更成:spring.datasource.jdbc-url和spring.datasource.driver-class-name即可解决!

 2.自定义配置文件

自定义配置文件需要在指定配置类上加上@propertysource标签,例如:

?

1

@propertysource (value = "classpath:config/mysql/db.properties" )

若是作用于配置类中的方法,则在方法上加上@configurationproperties,例如:

?

1

@configurationproperties (prefix = "spring.datasource.example" )

配置项前缀为spring.datasource.example

若是作用于配置类上,则在类上加上@configurationproperties(同上),并且在启动类上加上@enableconfigurationproperties(xxx.class)

3.多数据源

需要在启动类上取消自动装载数据源,如:

?

1

2

3

@springbootapplication (exclude = {

     datasourceautoconfiguration. class

})

以上所述是小编给大家介绍的spring boot + mybatis 实现动态数据源详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://HdhCmsTestcnblogs测试数据/fnlingnzb-learner/p/10710145.html#top

查看更多关于详解Spring Boot + Mybatis 实现动态数据源的详细内容...

  阅读:31次