1.动态数据源的作用:根据不同业务,访问不同数据库。最终解决的是提高用户访问速度,缓解数据库压力。例子:对于数据量大的表,单个数据库压力很大。查询速度很慢,需要水平分表。常见的做法是按照用户的账号进行hash,然后选择对应的数据库。
2方法:利用spring为我们提供了数据源切换类org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource来实现。
代码如下:
配置文件:配置多个数据源.
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
druid:
ds1:
url: jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
username: root
password: root
ds2:
url: jdbc:mysql://localhost:3306/test1?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
username: root
password: root
initial-size: 10
max-active: 100
min-idle: 10