Просмотр исходного кода

添加ShardingJdbc分库分表功能

Yue 2 лет назад
Родитель
Сommit
3d71c0a21c

+ 16 - 7
SERVER/VberAdminPlus/pom.xml

@@ -14,6 +14,8 @@
     <properties>
         <revision>1.0.0</revision>
         <spring-boot.version>2.7.13</spring-boot.version>
+        <shardingsphere.version>5.3.2</shardingsphere.version>
+        <dynamic-ds.version>3.5.2</dynamic-ds.version>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
         <java.version>1.8</java.version>
@@ -31,7 +33,6 @@
         <spring-boot-admin.version>2.7.10</spring-boot-admin.version>
         <redisson.version>3.20.1</redisson.version>
         <lock4j.version>2.2.3</lock4j.version>
-        <dynamic-ds.version>3.5.2</dynamic-ds.version>
         <alibaba-ttl.version>2.14.2</alibaba-ttl.version>
         <xxl-job.version>2.4.0</xxl-job.version>
         <lombok.version>1.18.26</lombok.version>
@@ -90,6 +91,20 @@
                 <scope>import</scope>
             </dependency>
 
+            <!-- dynamic-datasource 多数据源-->
+            <dependency>
+                <groupId>com.baomidou</groupId>
+                <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
+                <version>${dynamic-ds.version}</version>
+            </dependency>
+
+            <!-- shardingSphere 分库分表-->
+            <dependency>
+                <groupId>org.apache.shardingsphere</groupId>
+                <artifactId>shardingsphere-jdbc-core</artifactId>
+                <version>${shardingsphere.version}</version>
+            </dependency>
+
             <!-- hutool 的依赖配置-->
             <dependency>
                 <groupId>cn.hutool</groupId>
@@ -165,12 +180,6 @@
                 </exclusions>
             </dependency>
 
-            <!-- dynamic-datasource 多数据源-->
-            <dependency>
-                <groupId>com.baomidou</groupId>
-                <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
-                <version>${dynamic-ds.version}</version>
-            </dependency>
 
             <dependency>
                 <groupId>com.baomidou</groupId>

+ 98 - 0
SERVER/VberAdminPlus/vber-admin/src/main/resources/application-dev.yml

@@ -1,3 +1,101 @@
+--- # 分库分表配置
+vber:
+  shardingSphere:
+    enabled: true
+    database-name: vber_logic_db
+    mode:
+      type: Standalone
+      repository:
+        type: JDBC
+    dataSources:
+      # 主库数据源
+      master:
+        dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+        driverClassName: com.mysql.jdbc.Driver
+        url: jdbc:mysql://47.112.30.247:4501/VberAdminPlus?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+        username: root
+        password: Iwb2023
+    #      order1:
+    #        dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    #        driverClassName: com.mysql.cj.jdbc.Driver
+    #        url: jdbc:mysql://47.112.30.247:4501/ry-order1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+    #        username: root
+    #        password: Iwb2023
+    #      order2:
+    #        dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    #        driverClassName: com.mysql.cj.jdbc.Driver
+    #        url: jdbc:mysql://47.112.30.247:4501/ry-order2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+    #        username: root
+    #        password: Iwb2023
+    #      test2023:
+    #        dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    #        driverClassName: com.mysql.cj.jdbc.Driver
+    #        url: jdbc:mysql://47.112.30.247:4501/test_2023?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+    #        username: root
+    #        password: Iwb2023
+    #      test2024:
+    #        dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+    #        driverClassName: com.mysql.cj.jdbc.Driver
+    #        url: jdbc:mysql://47.112.30.247:4501/test_2024?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+    #        username: root
+    #        password: Iwb2023
+    # rules:
+    #      sharding:
+    #        tables:
+    #          sys_order:
+    #            logicTable: sys_order
+    #            actualDataNodes: order$->{1..2}.sys_order_$->{0..1}
+    #            keyGenerateStrategy:
+    #              column: order_id
+    #              keyGeneratorName: snow_flake
+    #            databaseStrategy:
+    #              standard:
+    #                sharding-column: user_id
+    #                sharding-algorithm-name: database_inline
+    #            tableStrategy:
+    #              standard:
+    #                sharding-column: order_id
+    #                sharding-algorithm-name: order_inline
+    #          t_user:
+    #            logicTable: t_user
+    #            actualDataNodes: test${2023..2024}.t_user_0${1..9},test${2023..2024}.t_user_${10..12}
+    #            databaseStrategy:
+    #              standard:
+    #                sharding-column: birthday
+    #                sharding-algorithm-name: database_long_date
+    #            tableStrategy:
+    #              standard:
+    #                sharding-column: birthday
+    #                sharding-algorithm-name: table_long_date
+    #        key-generators:
+    #          snow_flake:
+    #            type: SNOWFLAKE
+    #        sharding-algorithms:
+    #          database_inline:
+    #            type: INLINE
+    #            props:
+    #              algorithm-expression: order$->{(user_id % 2) + 1}
+    #          order_inline:
+    #            type: INLINE
+    #            props:
+    #              algorithm-expression: sys_order_$->{order_id % 2}
+    #          database_long_date:
+    #            type: CLASS_BASED
+    #            props:
+    #              strategy: STANDARD
+    #              algorithmClassName: com.vber.framework.sharding.LongDateShardingAlgorithm
+    #              first-index: 0
+    #              second-index: 4
+    #          table_long_date:
+    #            type: CLASS_BASED
+    #            props:
+    #              strategy: STANDARD
+    #              algorithmClassName: com.vber.framework.sharding.LongDateShardingAlgorithm
+    #              first-index: 4
+    #              second-index: 6
+    props:
+      sql.show: true
+
 --- # 监控中心配置
 spring.boot.admin.client:
   # 增加客户端开关

+ 22 - 0
SERVER/VberAdminPlus/vber-admin/src/main/resources/application-prod.yml

@@ -1,6 +1,28 @@
 --- # 临时文件存储位置 避免临时文件被系统清理报错
 spring.servlet.multipart.location: /vber/server/temp
 
+vber:
+  shardingSphere:
+    enabled: false
+    database-name: vber_logic_db
+    mode:
+      type: Standalone
+      repository:
+        type: JDBC
+    dataSources:
+      # 主库数据源
+      master:
+        dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+        driverClassName: com.mysql.jdbc.Driver
+        url: jdbc:mysql://47.112.30.247:4501/VberAdminPlus?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
+        username: root
+        password: Iwb2023
+    rules:
+    props:
+      sql.show: true
+
+
+
 --- # 监控中心配置
 spring.boot.admin.client:
   # 增加客户端开关

+ 2 - 0
SERVER/VberAdminPlus/vber-admin/src/main/resources/application.yml

@@ -12,6 +12,8 @@ vber:
   addressEnabled: true
   # 缓存懒加载
   cacheLazy: false
+  shardingSphere:
+    enabled: false
 
 captcha:
   # 页面 <参数设置> 可开启关闭 验证码校验

+ 21 - 0
SERVER/VberAdminPlus/vber-common/src/main/java/com/vber/common/constant/DataSourceConstants.java

@@ -0,0 +1,21 @@
+package com.vber.common.constant;
+
+/**
+ * 代码生成通用常量
+ */
+public interface DataSourceConstants {
+    /**
+     * 主库
+     */
+    String MASTER = "master";
+
+    ///**
+    // * 从库
+    // */
+    //String SLAVE = "slave";
+    /**
+     * 分库
+     */
+    String SHARD = "shard";
+
+}

+ 6 - 0
SERVER/VberAdminPlus/vber-framework/pom.xml

@@ -37,6 +37,12 @@
             <artifactId>spring-boot-starter-aop</artifactId>
         </dependency>
 
+        <!-- shardingSphere 分库分表-->
+        <dependency>
+            <groupId>org.apache.shardingsphere</groupId>
+            <artifactId>shardingsphere-jdbc-core</artifactId>
+        </dependency>
+        
         <!-- sql性能分析插件 -->
         <dependency>
             <groupId>p6spy</groupId>

+ 138 - 0
SERVER/VberAdminPlus/vber-framework/src/main/java/com/vber/framework/config/DataSourceConfig.java

@@ -0,0 +1,138 @@
+package com.vber.framework.config;
+
+import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
+import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
+import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
+import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
+import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
+import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
+import com.vber.common.constant.DataSourceConstants;
+import com.vber.framework.config.sharding.VberYamlRootConfiguration;
+import com.vber.framework.config.sharding.VberYamlShardingRuleConfiguration;
+import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
+import org.apache.shardingsphere.infra.yaml.config.pojo.YamlRootConfiguration;
+import org.apache.shardingsphere.sharding.yaml.config.YamlShardingRuleConfiguration;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigureBefore;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+import org.springframework.core.annotation.Order;
+
+import javax.sql.DataSource;
+import java.sql.SQLException;
+import java.util.Map;
+
+/**
+ * 动态数据源配置:
+ * <p>
+ * 使用{@link com.baomidou.dynamic.datasource.annotation.DS}注解,切换数据源
+ * <code>@DS(DataSourceConfiguration.SHARDING_DATA_SOURCE_NAME)</code>
+ */
+@Configuration
+@AutoConfigureBefore({DynamicDataSourceAutoConfiguration.class, SpringBootConfiguration.class})
+@ConditionalOnProperty(name = "vber.sharding-sphere.enabled", havingValue = "true", matchIfMissing = false)
+public class DataSourceConfig {
+    /**
+     * 分表数据源名称(默认使用主库)
+     */
+    public static final String SHARDING_DATA_SOURCE_NAME = DataSourceConstants.SHARD;
+
+    /**
+     * 分库分表规则
+     */
+    private final VberYamlShardingRuleConfiguration vberShardingRuleConfig;
+
+    /**
+     * 动态数据源配置项
+     */
+    private final DynamicDataSourceProperties properties;
+
+    public DataSourceConfig(VberYamlShardingRuleConfiguration vberShardingRuleConfig, DynamicDataSourceProperties dynamicDataSourceProperties) {
+        this.vberShardingRuleConfig = vberShardingRuleConfig;
+        this.properties = dynamicDataSourceProperties;
+    }
+
+
+    //@Bean(name = "shardDataSource")
+    public DataSource shardingDataSource(VberYamlRootConfiguration vberRootConfig) throws SQLException {
+        YamlRootConfiguration rootConfig = buildYamlRootConfiguration(vberRootConfig);
+        return YamlShardingSphereDataSourceFactory.createDataSourceWithoutCache(rootConfig);
+    }
+
+    @Bean
+    @Order(0)
+    public DynamicDataSourceProvider dynamicDataSourceProvider(VberYamlRootConfiguration vberRootConfig) {
+        Map<String, DataSourceProperty> datasourceMap = properties.getDatasource();
+        return new AbstractDataSourceProvider() {
+            @Override
+            public Map<String, DataSource> loadDataSources() {
+                Map<String, DataSource> dataSourceMap = createDataSourceMap(datasourceMap);
+                YamlRootConfiguration rootConfig = buildYamlRootConfiguration(vberRootConfig);
+                DataSource shardingDataSource = null;
+                try {
+                    shardingDataSource = YamlShardingSphereDataSourceFactory.createDataSourceWithoutCache(rootConfig);
+                } catch (SQLException e) {
+                    throw new RuntimeException(e);
+                }
+                // 将 shardingjdbc 管理的数据源也交给动态数据源管
+                dataSourceMap.put(SHARDING_DATA_SOURCE_NAME, shardingDataSource);
+                return dataSourceMap;
+            }
+        };
+    }
+
+    /**
+     * 将动态数据源设置为首选的
+     * 当spring存在多个数据源时, 自动注入的是首选的对象
+     * 设置为主要的数据源之后,就可以支持shardingjdbc原生的配置方式了
+     *
+     * @return DataSource
+     */
+    @Primary
+    @Bean
+    public DataSource dataSource() {
+        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
+        dataSource.setPrimary(SHARDING_DATA_SOURCE_NAME);
+        dataSource.setStrict(properties.getStrict());
+        dataSource.setStrategy(properties.getStrategy());
+        dataSource.setP6spy(properties.getP6spy());
+        dataSource.setSeata(properties.getSeata());
+        return dataSource;
+    }
+
+    /**
+     * 构建分库分表规则
+     *
+     * @param rootConfig yaml配置文件
+     * @return 配置规则
+     */
+    private YamlRootConfiguration buildYamlRootConfiguration(VberYamlRootConfiguration rootConfig) {
+        YamlRootConfiguration yamlRootConfig = new YamlRootConfiguration();
+        yamlRootConfig.setDataSources(rootConfig.getDataSources());
+        yamlRootConfig.setMode(rootConfig.getMode());
+        yamlRootConfig.setDatabaseName(rootConfig.getDatabaseName());
+        yamlRootConfig.setRules(rootConfig.getRules());
+        yamlRootConfig.setProps(rootConfig.getProps());
+
+        YamlShardingRuleConfiguration yamlShardingRuleConfig = new YamlShardingRuleConfiguration();
+        yamlShardingRuleConfig.setTables(vberShardingRuleConfig.getTables());
+        yamlShardingRuleConfig.setAutoTables(vberShardingRuleConfig.getAutoTables());
+        yamlShardingRuleConfig.setBindingTables(vberShardingRuleConfig.getBindingTables());
+        yamlShardingRuleConfig.setBroadcastTables(vberShardingRuleConfig.getBroadcastTables());
+        yamlShardingRuleConfig.setDefaultDatabaseStrategy(vberShardingRuleConfig.getDefaultDatabaseStrategy());
+        yamlShardingRuleConfig.setDefaultTableStrategy(vberShardingRuleConfig.getDefaultTableStrategy());
+        yamlShardingRuleConfig.setDefaultKeyGenerateStrategy(vberShardingRuleConfig.getDefaultKeyGenerateStrategy());
+        yamlShardingRuleConfig.setDefaultAuditStrategy(vberShardingRuleConfig.getDefaultAuditStrategy());
+        yamlShardingRuleConfig.setShardingAlgorithms(vberShardingRuleConfig.getShardingAlgorithms());
+        yamlShardingRuleConfig.setKeyGenerators(vberShardingRuleConfig.getKeyGenerators());
+        yamlShardingRuleConfig.setAuditors(vberShardingRuleConfig.getAuditors());
+        yamlShardingRuleConfig.setDefaultShardingColumn(vberShardingRuleConfig.getDefaultShardingColumn());
+        yamlRootConfig.getRules().add(yamlShardingRuleConfig);
+
+        return yamlRootConfig;
+    }
+
+
+}

+ 24 - 0
SERVER/VberAdminPlus/vber-framework/src/main/java/com/vber/framework/config/sharding/VberYamlRootConfiguration.java

@@ -0,0 +1,24 @@
+package com.vber.framework.config.sharding;
+
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.apache.shardingsphere.infra.util.yaml.YamlConfiguration;
+import org.apache.shardingsphere.infra.yaml.config.pojo.mode.YamlModeConfiguration;
+import org.apache.shardingsphere.infra.yaml.config.pojo.rule.YamlRuleConfiguration;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.*;
+
+@Data
+@Configuration
+@NoArgsConstructor
+@ConfigurationProperties(prefix = "vber.sharding-sphere")
+public class VberYamlRootConfiguration implements YamlConfiguration {
+    private Boolean enabled = false;
+    private String databaseName = "vber-logic-db";
+    private Map<String, Map<String, Object>> dataSources = new HashMap<>();
+    private Collection<YamlRuleConfiguration> rules = new LinkedList<>();
+    private YamlModeConfiguration mode;
+    private Properties props = new Properties();
+}

+ 46 - 0
SERVER/VberAdminPlus/vber-framework/src/main/java/com/vber/framework/config/sharding/VberYamlShardingRuleConfiguration.java

@@ -0,0 +1,46 @@
+package com.vber.framework.config.sharding;
+
+
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.apache.shardingsphere.infra.yaml.config.pojo.algorithm.YamlAlgorithmConfiguration;
+import org.apache.shardingsphere.infra.yaml.config.pojo.rule.YamlRuleConfiguration;
+import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
+import org.apache.shardingsphere.sharding.yaml.config.rule.YamlShardingAutoTableRuleConfiguration;
+import org.apache.shardingsphere.sharding.yaml.config.rule.YamlTableRuleConfiguration;
+import org.apache.shardingsphere.sharding.yaml.config.strategy.audit.YamlShardingAuditStrategyConfiguration;
+import org.apache.shardingsphere.sharding.yaml.config.strategy.keygen.YamlKeyGenerateStrategyConfiguration;
+import org.apache.shardingsphere.sharding.yaml.config.strategy.sharding.YamlShardingStrategyConfiguration;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+
+@Data
+@NoArgsConstructor
+@Configuration
+@ConfigurationProperties(prefix = "vber.sharding-sphere.rules.sharding")
+
+public class VberYamlShardingRuleConfiguration implements YamlRuleConfiguration {
+    private Map<String, YamlTableRuleConfiguration> tables = new LinkedHashMap<>();
+    private Map<String, YamlShardingAutoTableRuleConfiguration> autoTables = new LinkedHashMap<>();
+    private Collection<String> bindingTables = new LinkedList<>();
+    private Collection<String> broadcastTables = new LinkedList<>();
+    private YamlShardingStrategyConfiguration defaultDatabaseStrategy;
+    private YamlShardingStrategyConfiguration defaultTableStrategy;
+    private YamlKeyGenerateStrategyConfiguration defaultKeyGenerateStrategy;
+    private YamlShardingAuditStrategyConfiguration defaultAuditStrategy;
+    private Map<String, YamlAlgorithmConfiguration> shardingAlgorithms = new LinkedHashMap<>();
+    private Map<String, YamlAlgorithmConfiguration> keyGenerators = new LinkedHashMap<>();
+    private Map<String, YamlAlgorithmConfiguration> auditors = new LinkedHashMap<>();
+    private String defaultShardingColumn;
+
+
+    public Class<ShardingRuleConfiguration> getRuleConfigurationType() {
+        return ShardingRuleConfiguration.class;
+    }
+
+}

+ 73 - 0
SERVER/VberAdminPlus/vber-framework/src/main/java/com/vber/framework/sharding/LongDateShardingAlgorithm.java

@@ -0,0 +1,73 @@
+package com.vber.framework.sharding;
+
+import com.google.common.collect.Range;
+import lombok.Getter;
+import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
+import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
+import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
+
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Properties;
+
+@Getter
+public class LongDateShardingAlgorithm implements StandardShardingAlgorithm<Long> {
+
+    private Properties props;
+    private int firstIndex;
+    private int secondIndex;
+
+    @Override
+    public void init(Properties props) {
+        this.props = props;
+        firstIndex = this.getFirstIndex(props);
+        secondIndex = this.getSecondIndex(props);
+
+    }
+
+    private int getFirstIndex(Properties props) {
+        return Integer.parseInt(props.getProperty("first-index", "0"));
+    }
+
+    private int getSecondIndex(Properties props) {
+        return Integer.parseInt(String.valueOf(props.getProperty("second-index", "4")));
+    }
+
+    @Override
+    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
+        Long value = shardingValue.getValue();
+        String tableName = String.valueOf(value).substring(firstIndex, secondIndex);
+        for (String each : availableTargetNames) {
+            if (each.endsWith(tableName)) {
+                return each;
+            }
+        }
+        if (!availableTargetNames.isEmpty()) {
+            return (String) availableTargetNames.toArray()[0];
+        }
+        return "";
+
+    }
+
+    @Override
+    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
+        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
+        Range<Long> range = shardingValue.getValueRange();
+        int lowerEndPoint = Integer.parseInt(String.valueOf(range.lowerEndpoint()).substring(firstIndex, secondIndex));
+        int upperEndpoint = Integer.parseInt(String.valueOf(range.upperEndpoint()).substring(firstIndex, secondIndex));
+        for (Integer value = lowerEndPoint; value <= upperEndpoint; value++) {
+            String database_index = String.valueOf(value);
+            for (String each : availableTargetNames) {
+                if (each.endsWith(database_index)) {
+                    result.add(each);
+                }
+            }
+        }
+        if (result.isEmpty() && !availableTargetNames.isEmpty()) {
+            result.add((String) availableTargetNames.toArray()[0]);
+        }
+        return result;
+    }
+
+
+}

+ 22 - 28
SERVER/VberAdminPlus/vber-generator/src/main/java/com/vber/generator/controller/HomeController.java

@@ -1,15 +1,13 @@
 package com.vber.generator.controller;
 
 import cn.dev33.satoken.annotation.SaIgnore;
-import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
+import com.vber.common.constant.DataSourceConstants;
 import com.vber.common.core.controller.BaseController;
 import com.vber.common.core.domain.entity.SysDictType;
 import com.vber.common.core.domain.entity.SysMenu;
 import com.vber.generator.domain.ZTree;
 import com.vber.generator.service.IGenDictTypeService;
 import com.vber.generator.service.IGenMenuService;
-import com.vber.generator.service.IGenTableService;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -26,16 +24,11 @@ import java.util.List;
 @SaIgnore
 @Controller
 public class HomeController extends BaseController {
-    private final IGenTableService genTableService;
     private final IGenMenuService menuService;
     private final IGenDictTypeService dictTypeService;
 
-    @Autowired
-    private DynamicDataSourceAutoConfiguration dynamicDSConfig;
 
-
-    public HomeController(IGenTableService genTableService, IGenMenuService menuService, IGenDictTypeService dictTypeService) {
-        this.genTableService = genTableService;
+    public HomeController(IGenMenuService menuService, IGenDictTypeService dictTypeService) {
         this.menuService = menuService;
         this.dictTypeService = dictTypeService;
     }
@@ -44,7 +37,8 @@ public class HomeController extends BaseController {
      * 访问首页
      */
     @RequestMapping("/")
-    public String index() {
+    public String index(ModelMap mMap) {
+        mMap.put("dataSource", DataSourceConstants.MASTER);
         return "index";
     }
 
@@ -54,17 +48,17 @@ public class HomeController extends BaseController {
     }
 
     @GetMapping("/gen/importTable/{dataSource}")
-    public String importTable(@PathVariable("dataSource") String dataSource, ModelMap mmap) {
-        mmap.put("dataSource", dataSource);
+    public String importTable(@PathVariable("dataSource") String dataSource, ModelMap mMap) {
+        mMap.put("dataSource", dataSource);
         return "importTable";
     }
 
     @GetMapping("/gen/edit/{datasource}/{tableId}")
-    public String edit(@PathVariable("datasource") String datasource, @PathVariable("tableId") Long tableId, ModelMap mmap) {
+    public String edit(@PathVariable("datasource") String datasource, @PathVariable("tableId") Long tableId, ModelMap mMap) {
         List<SysDictType> dictList = dictTypeService.selectDictList();
-        mmap.put("tableId", tableId);
-        mmap.put("dictList", dictList);
-        mmap.put("datasource", datasource);
+        mMap.put("tableId", tableId);
+        mMap.put("dictList", dictList);
+        mMap.put("datasource", datasource);
         return "edit";
     }
 
@@ -72,9 +66,9 @@ public class HomeController extends BaseController {
      * 选择菜单树
      */
     @GetMapping("/gen/selectMenuTree/{menuId}")
-    public String selectMenuTree(@PathVariable("menuId") Long menuId, ModelMap mmap) {
+    public String selectMenuTree(@PathVariable("menuId") Long menuId, ModelMap mMap) {
         SysMenu menu = menuService.selectMenuById(menuId);
-        mmap.put("menu", menu);
+        mMap.put("menu", menu);
         return "tree/menuTree";
     }
 
@@ -93,9 +87,9 @@ public class HomeController extends BaseController {
      */
     @GetMapping("/gen/selectDictTree/{columnId}/{dictType}")
     public String selectDeptTree(@PathVariable("columnId") Long columnId, @PathVariable("dictType") String dictType,
-                                 ModelMap mmap) {
-        mmap.put("columnId", columnId);
-        mmap.put("dict", dictTypeService.selectDictTypeByType(dictType));
+                                 ModelMap mMap) {
+        mMap.put("columnId", columnId);
+        mMap.put("dict", dictTypeService.selectDictTypeByType(dictType));
         return "tree/dicTree";
     }
 
@@ -112,13 +106,13 @@ public class HomeController extends BaseController {
      * 加载字典列表树
      */
     @GetMapping("/gen/project")
-    public String project(ModelMap mmap) {
-        mmap.put("groupId", "com.vap");
-        mmap.put("artifactId", "VberAdminPlus");
-        mmap.put("packageName", "com.vber");
-        mmap.put("title", "VberAdminPlus后台管理系统");
-        mmap.put("modulePrefix", "vber-");
-        mmap.put("projectDir", "D:\\Project\\VbAdminPlus_New\\");
+    public String project(ModelMap mMap) {
+        mMap.put("groupId", "com.vap");
+        mMap.put("artifactId", "VberAdminPlus");
+        mMap.put("packageName", "com.vber");
+        mMap.put("title", "VberAdminPlus后台管理系统");
+        mMap.put("modulePrefix", "vber-");
+        mMap.put("projectDir", "D:\\Project\\VbAdminPlus_New\\");
         return "project";
     }
 }

+ 13 - 13
SERVER/VberAdminPlus/vber-generator/src/main/resources/templates/index.html

@@ -11,9 +11,9 @@
                 <div class="select-list">
                     <ul>
                         <li>
-                            数据源:<input name="dataName" onchange="changeDataSource(this)"
-                                          placeholder="请输入数据源名称" type="text"
-                                          value="master"/>
+                            数据源:<input name="dataSource" onchange="changeDataSource(this)"
+                                          placeholder="请输入数据源名称" th:value="${dataSource}"
+                                          type="text"/>
                         </li>
                         <li>
                             表名称:<input name="tableName" placeholder="请输入表名称" type="text"/>
@@ -76,11 +76,11 @@
     var removeFlag = "";
     var previewFlag = "";
     var codeFlag = "";
-
+    const $dataSource = $("#gen-form input[name='dataSource']");
     var options = {
         url: prefix + "/list",
         ajaxOptions: {
-            headers: {"datasource": "master"}
+            headers: {"datasource": $dataSource.val()}
         },
         method: "get",
         updateUrl: prefix + "/edit/{id}",
@@ -184,7 +184,7 @@
     }
 
     function changeDataSource(that) {
-        //.ajaxOptions.headers.datasource = $("#gen-form input[name='dataName']").val();
+        //.ajaxOptions.headers.datasource = $dataSource.val();
         options.ajaxOptions.headers.datasource = $(that).val();
         $.table.refreshOptions(options, "bootstrap-table");
     }
@@ -196,7 +196,7 @@
     function update(id) {
         id = id || $.table.selectColumns()[0].tableId
         //console.log(id)
-        window.open(`/gen/edit/${$("#gen-form input[name='dataName']").val()}/${id}`, "修改表信息")
+        window.open(`/gen/edit/${$dataSource.val()}/${id}`, "修改表信息")
     }
 
     function projectReactor() {
@@ -219,7 +219,7 @@
         $.operate.get({
             url: preViewUrl,
             headers: {
-                datasource: $("#gen-form input[name='dataName']").val()
+                datasource: $dataSource.val()
             },
             callback: function (result) {
                 if (result.code == web_status.SUCCESS) {
@@ -267,7 +267,7 @@
                     url: url,
                     type: "post",
                     headers: {
-                        datasource: $("#gen-form input[name='dataName']").val()
+                        datasource: $dataSource.val()
                     },
                     success: (res) => {
                         if (res.code == web_status.SUCCESS) {
@@ -283,7 +283,7 @@
                 $.operate.get({
                     url: prefix + "/genCode/" + tableName,
                     headers: {
-                        datasource: $("#gen-form input[name='dataName']").val()
+                        datasource: $dataSource.val()
                     },
                 });
             }
@@ -296,7 +296,7 @@
             $.operate.get({
                 url: prefix + "/synchDb/" + tableName,
                 headers: {
-                    datasource: $("#gen-form input[name='dataName']").val()
+                    datasource: $dataSource.val()
                 },
             });
         })
@@ -316,7 +316,7 @@
                 url: url,
                 type: "post",
                 headers: {
-                    datasource: $("#gen-form input[name='dataName']").val()
+                    datasource: $dataSource.val()
                 },
                 success: (res) => {
                     if (res.code == web_status.SUCCESS) {
@@ -333,7 +333,7 @@
 
     // 导入表结构
     function importTable() {
-        var importTableUrl = prefix + "/importTable/" + $("#gen-form input[name='dataName']").val();
+        var importTableUrl = prefix + "/importTable/" + $dataSource.val();
         $.modal.open("导入表结构", importTableUrl);
     }
 

+ 2 - 1
SERVER/VberAdminPlus/vber-system/src/main/java/com/vber/system/service/impl/SysConfigServiceImpl.java

@@ -6,6 +6,7 @@ import com.baomidou.dynamic.datasource.annotation.DS;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.vber.common.constant.CacheNames;
+import com.vber.common.constant.DataSourceConstants;
 import com.vber.common.constant.UserConstants;
 import com.vber.common.core.domain.PageQuery;
 import com.vber.common.core.page.TableDataInfo;
@@ -55,7 +56,7 @@ public class SysConfigServiceImpl implements ISysConfigService, ConfigService {
      * @return 参数配置信息
      */
     @Override
-    @DS("master")
+    @DS(DataSourceConstants.MASTER)
     public SysConfig selectConfigById(Long configId) {
         return baseMapper.selectById(configId);
     }