Spring动态注册多数据源的实现方法

上一篇 / 下一篇  2018-03-14 14:01:18 / 个人分类:软件开发

最近在做SaaS应用,数据库采用了单实例多schema的架构(详见参考资料1),每个租户有一个独立的schema,同时整个数据源有一个共享的schema,因此需要解决动态增删、切换数据源的问题。

在网上搜了很多文章后,很多都是讲主从数据源配置,或都是在应用启动前已经确定好数据源配置的,甚少讲在不停机的情况如何动态加载数据源,所以写下这篇文章,以供参考。

使用到的技术

  • Java8
  • Spring + SpringMVC + MyBatis
  • Druid连接池
  • Lombok
  • (以上技术并不影响思路实现,只是为了方便浏览以下代码片段)

思路

当一个请求进来的时候,判断当前用户所属租户,并根据租户信息切换至相应数据源,然后进行后续的业务操作。

代码实现

  1. TenantConfigEntity(租户信息)
  2. @EqualsAndHashCode(callSuper = false)
  3. @Data
  4. @FieldDefaults(level = AccessLevel.PRIVATE)
  5. public class TenantConfigEntity {
  6. /**
  7. * 租户id
  8. **/
  9. Integer tenantId;
  10. /**
  11. * 租户名称
  12. **/
  13. String tenantName;
  14. /**
  15. * 租户名称key
  16. **/
  17. String tenantKey;
  18. /**
  19. * 数据库url
  20. **/
  21. String dbUrl;
  22. /**
  23. * 数据库用户名
  24. **/
  25. String dbUser;
  26. /**
  27. * 数据库密码
  28. **/
  29. String dbPassword;
  30. /**
  31. * 数据库public_key
  32. **/
  33. String dbPublicKey;
  34. }
  35. DataSourceUtil(辅助工具类,非必要)
  36. public class DataSourceUtil {
  37. private static final String DATA_SOURCE_BEAN_KEY_SUFFIX = "_data_source";
  38. private static final String JDBC_URL_ARGS = "?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&zeroDateTimeBehavior=convertToNull";
  39. private static final String CONNECTION_PROPERTIES = "config.decrypt=true;config.decrypt.key=";
  40. /**
  41. * 拼接数据源的spring bean key
  42. */
  43. public static String getDataSourceBeanKey(String tenantKey) {
  44. if (!StringUtils.hasText(tenantKey)) {
  45. return null;
  46. }
  47. return tenantKey + DATA_SOURCE_BEAN_KEY_SUFFIX;
  48. }
  49. /**
  50. * 拼接完整的JDBC URL
  51. */
  52. public static String getJDBCUrl(String baseUrl) {
  53. if (!StringUtils.hasText(baseUrl)) {
  54. return null;
  55. }
  56. return baseUrl + JDBC_URL_ARGS;
  57. }
  58. /**
  59. * 拼接完整的Druid连接属性
  60. */
  61. public static String getConnectionProperties(String publicKey) {
  62. if (!StringUtils.hasText(publicKey)) {
  63. return null;
  64. }
  65. return CONNECTION_PROPERTIES + publicKey;
  66. }
  67. }
复制代码

DataSourceContextHolder

使用 ThreadLocal 保存当前线程的数据源key name,并实现set、get、clear方法;

  1. public class DataSourceContextHolder {
  2. private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<>();
  3. public static void setDataSourceKey(String tenantKey) {
  4. dataSourceKey.set(tenantKey);
  5. }
  6. public static String getDataSourceKey() {
  7. return dataSourceKey.get();
  8. }
  9. public static void clearDataSourceKey() {
  10. dataSourceKey.remove();
  11. }
  12. }
复制代码

DynamicDataSource(重点)

继承 AbstractRoutingDataSource (建议阅读其源码,了解动态切换数据源的过程),实现动态选择数据源;

  1. public class DynamicDataSource extends AbstractRoutingDataSource {
  2. @Autowired
  3. private ApplicationContext applicationContext;
  4. @Lazy
  5. @Autowired
  6. private DynamicDataSourceSummoner summoner;
  7. @Lazy
  8. @Autowired
  9. private TenantConfigDAO tenantConfigDAO;
  10. @Override
  11. protected String determineCurrentLookupKey() {
  12. String tenantKey = DataSourceContextHolder.getDataSourceKey();
  13. return DataSourceUtil.getDataSourceBeanKey(tenantKey);
  14. }
  15. @Override
  16. protected DataSource determineTargetDataSource() {
  17. String tenantKey = DataSourceContextHolder.getDataSourceKey();
  18. String beanKey = DataSourceUtil.getDataSourceBeanKey(tenantKey);
  19. if (!StringUtils.hasText(tenantKey) || applicationContext.containsBean(beanKey)) {
  20. return super.determineTargetDataSource();
  21. }
  22. if (tenantConfigDAO.exist(tenantKey)) {
  23. summoner.registerDynamicDataSources();
  24. }
  25. return super.determineTargetDataSource();
  26. }
  27. }
复制代码

DynamicDataSourceSummoner(重点中的重点)

从数据库加载数据源信息,并动态组装和注册spring bean,

  1. @Slf4j
  2. @Component
  3. public class DynamicDataSourceSummoner implements ApplicationListener<ContextRefreshedEvent> {
  4. // 跟spring-data-source.xml的默认数据源id保持一致
  5. private static final String DEFAULT_DATA_SOURCE_BEAN_KEY = "defaultDataSource";
  6. @Autowired
  7. private ConfigurableApplicationContext applicationContext;
  8. @Autowired
  9. private DynamicDataSource dynamicDataSource;
  10. @Autowired
  11. private TenantConfigDAO tenantConfigDAO;
  12. private static boolean loaded = false;
  13. /**
  14. * Spring加载完成后执行
  15. */
  16. @Override
  17. public void onApplicationEvent(ContextRefreshedEvent event) {
  18. // 防止重复执行
  19. if (!loaded) {
  20. loaded = true;
  21. try {
  22. registerDynamicDataSources();
  23. } catch (Exception e) {
  24. log.error("数据源初始化失败, Exception:", e);
  25. }
  26. }
  27. }
  28. /**
  29. * 从数据库读取租户的DB配置,并动态注入Spring容器
  30. */
  31. public void registerDynamicDataSources() {
  32. // 获取所有租户的DB配置
  33. List<TenantConfigEntity> tenantConfigEntities = tenantConfigDAO.listAll();
  34. if (CollectionUtils.isEmpty(tenantConfigEntities)) {
  35. throw new IllegalStateException("应用程序初始化失败,请先配置数据源");
  36. }
  37. // 把数据源bean注册到容器中
  38. addDataSourceBeans(tenantConfigEntities);
  39. }
  40. /**
  41. * 根据DataSource创建bean并注册到容器中
  42. */
  43. private void addDataSourceBeans(List<TenantConfigEntity> tenantConfigEntities) {
  44. Map<Object, Object> targetDataSources = Maps.newLinkedHashMap();
  45. DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
  46. for (TenantConfigEntity entity : tenantConfigEntities) {
  47. String beanKey = DataSourceUtil.getDataSourceBeanKey(entity.getTenantKey());
  48. // 如果该数据源已经在spring里面注册过,则不重新注册
  49. if (applicationContext.containsBean(beanKey)) {
  50. DruidDataSource existsDataSource = applicationContext.getBean(beanKey, DruidDataSource.class);
  51. if (isSameDataSource(existsDataSource, entity)) {
  52. continue;
  53. }
  54. }
  55. // 组装bean
  56. AbstractBeanDefinition beanDefinition = getBeanDefinition(entity, beanKey);
  57. // 注册bean
  58. beanFactory.registerBeanDefinition(beanKey, beanDefinition);
  59. // 放入map中,注意一定是刚才创建bean对象
  60. targetDataSources.put(beanKey, applicationContext.getBean(beanKey));
  61. }
  62. // 将创建的map对象set到 targetDataSources;
  63. dynamicDataSource.setTargetDataSources(targetDataSources);
  64. // 必须执行此操作,才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources,也只有这样,动态切换才会起效
  65. dynamicDataSource.afterPropertiesSet();
  66. }
  67. /**
  68. * 组装数据源spring bean
  69. */
  70. private AbstractBeanDefinition getBeanDefinition(TenantConfigEntity entity, String beanKey) {
  71. BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(DruidDataSource.class);
  72. builder.getBeanDefinition().setAttribute("id", beanKey);
  73. // 其他配置继承defaultDataSource
  74. builder.setParentName(DEFAULT_DATA_SOURCE_BEAN_KEY);
  75. builder.setInitMethodName("init");
  76. builder.setDestroyMethodName("close");
  77. builder.addPropertyValue("name", beanKey);
  78. builder.addPropertyValue("url", DataSourceUtil.getJDBCUrl(entity.getDbUrl()));
  79. builder.addPropertyValue("username", entity.getDbUser());
  80. builder.addPropertyValue("password", entity.getDbPassword());
  81. builder.addPropertyValue("connectionProperties", DataSourceUtil.getConnectionProperties(entity.getDbPublicKey()));
  82. return builder.getBeanDefinition();
  83. }
  84. /**
  85. * 判断Spring容器里面的DataSource与数据库的DataSource信息是否一致
  86. * 备注:这里没有判断public_key,因为另外三个信息基本可以确定唯一了
  87. */
  88. private boolean isSameDataSource(DruidDataSource existsDataSource, TenantConfigEntity entity) {
  89. boolean sameUrl = Objects.equals(existsDataSource.getUrl(), DataSourceUtil.getJDBCUrl(entity.getDbUrl()));
  90. if (!sameUrl) {
  91. return false;
  92. }
  93. boolean sameUser = Objects.equals(existsDataSource.getUsername(), entity.getDbUser());
  94. if (!sameUser) {
  95. return false;

TAG:

 

评分:0

我来说两句