1、通过切面的方式进行数据源的切换;切的是 注解@DataSoure;@Pointcut("@annotation(com.manage.common.annotation.DataSource)"
+ "|| @within(com.manage.common.annotation.DataSource)")
2、然后切面获取当前的方法的注解中所要切换的数据库
3、设置数据源的变量ThreadLocal<String> CONTEXT_HOLDER.set(dsType); (
什么是ThreadLocal
ThreadLocal是java中的线程本地变量,用于每个线程保存自己的变量,使线程间的变量互不干扰。
使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
)
4、使用 AbstractRoutingDataSource实现动态数据源切换
1.定义DynamicDataSource类继承抽象类AbstractRoutingDataSource,并实现了determineCurrentLookupKey()方法。
2.把配置的多个数据源会放在AbstractRoutingDataSource的 targetDataSources和defaultTargetDataSource中,然后通过afterPropertiesSet()方法将数据源分别进行复制到resolvedDataSources和resolvedDefaultDataSource中。
3.调用AbstractRoutingDataSource的getConnection()的方法的时候,先调用determineTargetDataSource()方法返回DataSource在进行getConnection()。
数据源配置 这里用的是postgresql
# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: org.postgresql.Driver
druid:
# 主库数据源
system:
url: jdbc:postgresql://192....207:12004/db_system?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: postgres
password: DB$zs#H9KhA$t.....z%THI%q4^PYS
# 从库数据源
template:
# 从数据源开关/默认关闭/captchaImage
enabled: true
url: jdbc:postgresql://192....207:12004/db_work_template?autoReconnect=true&&useSSL=true
username: postgres
password: DB$zs#H9KhA$t.....z%THI%q4^PYS
# 从库数据源
log:
# 从数据源开关/默认关闭/captchaImage
enabled: true
url: jdbc:postgresql://192....207:12004/db_work_log?autoReconnect=true&&useSSL=true
username: postgres
password: DB$zs#H9KhA$t.....z%THI%q4^PYS
# 从库数据源
event:
# 从数据源开关/默认关闭/captchaImage
enabled: true
url: jdbc:postgresql://192....207:12004/db_work_event?autoReconnect=true&&useSSL=true
username: postgres
password: DB$zs#H9KhA$t.....z%THI%q4^PYS
# 从库数据源
statis:
# 从数据源开关/默认关闭/captchaImage
enabled: true
url: jdbc:postgresql://192....207:12004/db_work_statis?autoReconnect=true&&useSSL=true
username: postgres
password: DB$zs#H9KhA$t.....z%THI%q4^PYS
# 从库数据源
allelism:
# 从数据源开关/默认关闭/captchaImage
enabled: true
url: jdbc:postgresql://192....207:12004/db_allelism?autoReconnect=true&&useSSL=true
username: postgres
password: DB$zs#H9KhA$t.....z%THI%q4^PYS
# 从库数据源
activiti:
# 从数据源开关/默认关闭/captchaImage
enabled: true
url: jdbc:postgresql://192....207:12004/db_activiti?autoReconnect=true&&useSSL=true
username: postgres
password: DB$zs#H9KhA$t.....z%THI%q4^PYS
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictabl