Browse Source

优化动态数据源

zhouhao 8 years ago
parent
commit
7f77aaddf7

+ 23 - 0
hsweb-web-controller/src/main/java/org/hsweb/web/controller/system/DatabaseManagerController.java

@@ -17,6 +17,9 @@ import org.hsweb.web.core.message.ResponseMessage;
 import org.hsweb.web.core.utils.WebUtil;
 import org.hsweb.web.service.form.DynamicFormService;
 import org.hsweb.web.service.system.DataBaseManagerService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
@@ -31,9 +34,25 @@ import java.util.List;
 @Authorize(module = "database")
 @AccessLogger("数据库管理")
 public class DatabaseManagerController {
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
     @Resource
     private DataBaseManagerService dataBaseManagerService;
 
+    @Autowired(required = false)
+    protected DynamicDataSource dynamicDataSource;
+
+    protected void checkDynamicDataSourceSupport() {
+        if (dynamicDataSource == null)
+            logger.warn("\ndynamicDataSource is not support! if you want use it,please import " +
+                    "\n<!--------------------------------------------------------->\n" +
+                    "       <dependency>\n" +
+                    "            <groupId>org.hsweb</groupId>\n" +
+                    "            <artifactId>hsweb-web-datasource</artifactId>\n" +
+                    "       </dependency>" +
+                    "\n<!--------------------------------------------------------->" +
+                    "\n to pom.xml");
+    }
+
     @RequestMapping(value = "/tables", method = RequestMethod.GET)
     @Authorize(action = "R")
     @AccessLogger("获取所有表结构")
@@ -67,6 +86,7 @@ public class DatabaseManagerController {
     @AccessLogger("指定数据源获取表结构")
     public ResponseMessage showTables(@PathVariable("dataSourceId") String dataSourceId) throws SQLException {
         try {
+            checkDynamicDataSourceSupport();
             DynamicDataSource.use(dataSourceId);
             return ResponseMessage.ok(dataBaseManagerService.getTableList())
                     .include(TableMetaData.class, "name", "alias", "comment", "fields")
@@ -109,6 +129,7 @@ public class DatabaseManagerController {
     @RequestMapping(value = "/exec/{dataSourceId}", method = RequestMethod.POST)
     @AccessLogger("指定数据源执行SQL")
     public ResponseMessage exec(@PathVariable("dataSourceId") String dataSourceId, @RequestBody String sql) throws Exception {
+        checkDynamicDataSourceSupport();
         DynamicDataSource.use(dataSourceId);
         try {
             return ResponseMessage.ok(dataBaseManagerService.execSql(buildSqlList(sql)));
@@ -121,6 +142,7 @@ public class DatabaseManagerController {
     @AccessLogger("指定数据源查询修改表结构SQL")
     public ResponseMessage showAlterSql(@PathVariable("dataSourceId") String dataSourceId, @RequestBody JSONObject jsonObject) throws Exception {
         try {
+            checkDynamicDataSourceSupport();
             DynamicDataSource.use(dataSourceId);
             return ResponseMessage.ok(dataBaseManagerService.createAlterSql(createTableMetaDataByJson(jsonObject)));
         } finally {
@@ -132,6 +154,7 @@ public class DatabaseManagerController {
     @AccessLogger("指定数据源查询创建表结构SQL")
     public ResponseMessage showCreateSql(@PathVariable("dataSourceId") String dataSourceId, @RequestBody JSONObject jsonObject) throws Exception {
         try {
+            checkDynamicDataSourceSupport();
             DynamicDataSource.use(dataSourceId);
             return ResponseMessage.ok(dataBaseManagerService.createCreateSql(createTableMetaDataByJson(jsonObject)));
         } finally {

+ 7 - 10
hsweb-web-datasource/pom.xml

@@ -28,17 +28,17 @@
     <artifactId>hsweb-web-datasource</artifactId>
 
     <dependencies>
-        <!--atomikos-->
         <dependency>
             <groupId>com.h2database</groupId>
             <artifactId>h2</artifactId>
             <scope>test</scope>
         </dependency>
 
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-web</artifactId>
-        </dependency>
+        <!--<dependency>-->
+            <!--<groupId>org.springframework.boot</groupId>-->
+            <!--<artifactId>spring-boot-starter-web</artifactId>-->
+        <!--</dependency>-->
+
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-jdbc</artifactId>
@@ -63,8 +63,10 @@
             <groupId>com.alibaba</groupId>
             <artifactId>druid</artifactId>
             <version>1.0.20</version>
+            <scope>test</scope>
         </dependency>
 
+        <!--atomikos-->
         <dependency>
             <groupId>com.atomikos</groupId>
             <artifactId>transactions-jdbc</artifactId>
@@ -95,10 +97,5 @@
             <artifactId>jta</artifactId>
         </dependency>
 
-        <dependency>
-            <groupId>org.mybatis.spring.boot</groupId>
-            <artifactId>mybatis-spring-boot-autoconfigure</artifactId>
-            <version>1.0.2</version>
-        </dependency>
     </dependencies>
 </project>

+ 16 - 8
hsweb-web-datasource/src/main/java/org/hsweb/web/datasource/dynamic/DynamicDataSourceAutoConfiguration.java

@@ -20,9 +20,15 @@ import com.atomikos.icatch.jta.UserTransactionImp;
 import com.atomikos.icatch.jta.UserTransactionManager;
 import com.atomikos.jdbc.AtomikosDataSourceBean;
 import org.hsweb.commons.StringUtils;
+import org.hsweb.web.core.datasource.DynamicDataSource;
+import org.hsweb.web.service.datasource.DynamicDataSourceService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
 import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
 import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.annotation.Primary;
 import org.springframework.transaction.jta.JtaTransactionManager;
@@ -30,17 +36,16 @@ import org.springframework.transaction.jta.JtaTransactionManager;
 import javax.sql.DataSource;
 import javax.transaction.SystemException;
 
-/**
- * Created by zhouhao on 16-4-20.
- */
 @Configuration
+@ConditionalOnMissingBean(DynamicDataSource.class)
+@ComponentScan("org.hsweb.web.datasource.dynamic")
 public class DynamicDataSourceAutoConfiguration {
 
     @Autowired
     private DataSourceProperties properties;
 
     static {
-//        com.atomikos.icatch.config.Configuration.init();
+        //  com.atomikos.icatch.config.Configuration.init();
         //  com.atomikos.icatch.config.Configuration.installCompositeTransactionManager(new CompositeTransactionManagerImp());
     }
 
@@ -60,15 +65,18 @@ public class DynamicDataSourceAutoConfiguration {
         return dataSourceBean;
     }
 
+    @Bean(name = "dynamicDataSource")
+    public DynamicXaDataSourceImpl dynamicXaDataSource(@Qualifier("dataSource") DataSource dataSource) {
+        return new DynamicXaDataSourceImpl(dataSource);
+    }
+
     /**
      * 动态数据源
-     * @param dataSource 默认数据源
-     * @return 动态数据源
      */
     @Bean(initMethod = "init", destroyMethod = "close")
-    public AtomikosDataSourceBean atomikosDataSourceBean(DataSource dataSource) {
+    public AtomikosDataSourceBean atomikosDataSourceBean(DynamicXaDataSourceImpl dynamicDataSource) {
         AtomikosDataSourceBean dataSourceBean = new AtomikosDataSourceBean();
-        dataSourceBean.setXaDataSource(new DynamicXaDataSourceImpl(dataSource));
+        dataSourceBean.setXaDataSource(dynamicDataSource);
         dataSourceBean.setUniqueResourceName("dynamic");
         dataSourceBean.setMaxPoolSize(StringUtils.toInt(properties.getXa().getProperties().get("maxPoolSize"), 200));
         dataSourceBean.setBorrowConnectionTimeout(30);

+ 5 - 11
hsweb-web-datasource/src/main/java/org/hsweb/web/datasource/dynamic/DynamicDataSourceServiceImpl.java

@@ -49,16 +49,10 @@ public class DynamicDataSourceServiceImpl implements DynamicDataSourceService {
     private DataSourceService dataSourceService;
 
     @Autowired(required = false)
-    @Qualifier("atomikosDataSourceBean")
-    private AtomikosDataSourceBean atomikosDataSourceBean;
+    protected DynamicDataSource dynamicDataSource;
 
     @Autowired
     private LockFactory lockFactory;
-//    @Resource
-//    private DynamicDeployBeans dynamicDeployBeans;
-
-//    @Autowired
-//    ApplicationContext applicationContext;
 
     private ConcurrentMap<String, CacheInfo> cache = new ConcurrentHashMap<>();
 
@@ -76,8 +70,7 @@ public class DynamicDataSourceServiceImpl implements DynamicDataSourceService {
     protected void closeDataSource(javax.sql.DataSource ds) {
         if (ds instanceof AtomikosDataSourceBean) {
             ((AtomikosDataSourceBean) ds).close();
-        }
-        if (ds instanceof Closeable) {
+        } else if (ds instanceof Closeable) {
             try {
                 ((Closeable) ds).close();
             } catch (IOException e) {
@@ -151,6 +144,7 @@ public class DynamicDataSourceServiceImpl implements DynamicDataSourceService {
         try {
             dataSourceBean.init();
         } catch (AtomikosSQLException e) {
+            dataSourceBean.close();
             throw new RuntimeException(e);
         }
         return dataSourceBean;
@@ -158,8 +152,8 @@ public class DynamicDataSourceServiceImpl implements DynamicDataSourceService {
 
     @PostConstruct
     public void init() {
-        if (null != atomikosDataSourceBean)
-            ((DynamicXaDataSourceImpl) atomikosDataSourceBean.getXaDataSource()).setDynamicDataSourceService(this);
+        if (null != dynamicDataSource)
+            ((DynamicXaDataSourceImpl) dynamicDataSource).setDynamicDataSourceService(this);
     }
 
     class CacheInfo {

+ 3 - 4
hsweb-web-datasource/src/main/java/org/hsweb/web/datasource/dynamic/DynamicDataSourceSqlExecutorService.java

@@ -16,7 +16,6 @@
 
 package org.hsweb.web.datasource.dynamic;
 
-import com.atomikos.jdbc.AtomikosDataSourceBean;
 import org.hsweb.ezorm.executor.AbstractJdbcSqlExecutor;
 import org.hsweb.ezorm.executor.SQL;
 import org.hsweb.ezorm.meta.expand.ObjectWrapper;
@@ -38,16 +37,16 @@ import java.util.Map;
 public class DynamicDataSourceSqlExecutorService extends AbstractJdbcSqlExecutor {
 
     @Resource
-    protected AtomikosDataSourceBean atomikosDataSourceBean;
+    protected DynamicDataSource dynamicDataSource;
 
     @Override
     public Connection getConnection() {
-        return DataSourceUtils.getConnection(((DynamicDataSource) atomikosDataSourceBean.getXaDataSource()).getActiveDataSource());
+        return DataSourceUtils.getConnection(dynamicDataSource.getActiveDataSource());
     }
 
     @Override
     public void releaseConnection(Connection connection) throws SQLException {
-        DataSourceUtils.releaseConnection(connection, ((DynamicDataSource) atomikosDataSourceBean.getXaDataSource()).getActiveDataSource());
+        DataSourceUtils.releaseConnection(connection, dynamicDataSource.getActiveDataSource());
     }
 
     @Override

+ 0 - 30
hsweb-web-service-impl-common/pom.xml

@@ -58,36 +58,6 @@
             <scope>test</scope>
         </dependency>
 
-        <!--<dependency>-->
-            <!--<groupId>com.atomikos</groupId>-->
-            <!--<artifactId>transactions-jdbc</artifactId>-->
-        <!--</dependency>-->
-
-        <!--<dependency>-->
-            <!--<groupId>com.atomikos</groupId>-->
-            <!--<artifactId>transactions-jta</artifactId>-->
-        <!--</dependency>-->
-
-        <!--<dependency>-->
-            <!--<groupId>com.atomikos</groupId>-->
-            <!--<artifactId>transactions</artifactId>-->
-        <!--</dependency>-->
-
-        <!--<dependency>-->
-            <!--<groupId>com.atomikos</groupId>-->
-            <!--<artifactId>transactions-api</artifactId>-->
-        <!--</dependency>-->
-
-        <!--<dependency>-->
-            <!--<groupId>com.atomikos</groupId>-->
-            <!--<artifactId>atomikos-util</artifactId>-->
-        <!--</dependency>-->
-
-        <!--<dependency>-->
-            <!--<groupId>javax.transaction</groupId>-->
-            <!--<artifactId>jta</artifactId>-->
-        <!--</dependency>-->
-
         <dependency>
             <groupId>org.hsweb</groupId>
             <artifactId>hsweb-expands-office</artifactId>

+ 28 - 1
hsweb-web-service-impl-common/src/main/java/org/hsweb/web/service/impl/datasource/DataSourceServiceImpl.java

@@ -20,6 +20,7 @@ import org.hsweb.web.bean.common.QueryParam;
 import org.hsweb.web.bean.common.UpdateMapParam;
 import org.hsweb.web.bean.common.UpdateParam;
 import org.hsweb.web.bean.po.datasource.DataSource;
+import org.hsweb.web.core.datasource.DynamicDataSource;
 import org.hsweb.web.core.exception.BusinessException;
 import org.hsweb.web.dao.datasource.DataSourceMapper;
 import org.hsweb.web.service.config.ConfigService;
@@ -33,6 +34,7 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
 
+import javax.annotation.PostConstruct;
 import javax.annotation.Resource;
 import java.util.Date;
 import java.util.List;
@@ -55,6 +57,27 @@ public class DataSourceServiceImpl extends AbstractServiceImpl<DataSource, Strin
     @Resource
     protected ConfigService configService;
 
+    @Autowired(required = false)
+    protected DynamicDataSource dynamicDataSource;
+
+
+    @PostConstruct
+    public void init() {
+        checkDynamicDataSourceSupport();
+    }
+
+    protected void checkDynamicDataSourceSupport() {
+        if (dynamicDataSource == null)
+            logger.warn("\ndynamicDataSource is not support! if you want use it,please import " +
+                    "\n<!--------------------------------------------------------->\n" +
+                    "       <dependency>\n" +
+                    "            <groupId>org.hsweb</groupId>\n" +
+                    "            <artifactId>hsweb-web-datasource</artifactId>\n" +
+                    "       </dependency>" +
+                    "\n<!--------------------------------------------------------->" +
+                    "\n to pom.xml");
+    }
+
     @Override
     protected DataSourceMapper getMapper() {
         return this.dataSourceMapper;
@@ -69,6 +92,7 @@ public class DataSourceServiceImpl extends AbstractServiceImpl<DataSource, Strin
 
     @Override
     public String insert(DataSource data) {
+        checkDynamicDataSourceSupport();
         data.setCreateDate(new Date());
         data.setEnabled(1);
         tryValidPo(data);
@@ -86,22 +110,25 @@ public class DataSourceServiceImpl extends AbstractServiceImpl<DataSource, Strin
     @Override
     @CacheEvict(value = CACHE_NAME, key = "'id:'+#data.id")
     public int update(DataSource data) {
+        checkDynamicDataSourceSupport();
         DataSource old = selectSingle(QueryParam.build()
                 .where("name", data.getName())
                 .and("id$not", data.getId()));
         if (old != null) throw new BusinessException("名称" + data.getName() + "已存在");
-        return getMapper().update(UpdateParam.build(data).excludes("createDate", "enabled").where("id",data.getId()));
+        return getMapper().update(UpdateParam.build(data).excludes("createDate", "enabled").where("id", data.getId()));
     }
 
     @Override
     @CacheEvict(value = CACHE_NAME, key = "'id:'+#id")
     public void enable(String id) {
+        checkDynamicDataSourceSupport();
         getMapper().update((UpdateParam) UpdateMapParam.build().set("enabled", 1).where("id", id));
     }
 
     @Override
     @CacheEvict(value = CACHE_NAME, key = "'id:'+#id")
     public void disable(String id) {
+        checkDynamicDataSourceSupport();
         getMapper().update((UpdateParam) UpdateMapParam.build().set("enabled", 0).where("id", id));
     }
 

+ 3 - 1
hsweb-web-service-impl-common/src/main/java/org/hsweb/web/service/impl/system/DataBaseManagerServiceImpl.java

@@ -21,6 +21,8 @@ import org.hsweb.web.core.exception.NotFoundException;
 import org.hsweb.web.service.datasource.DataSourceService;
 import org.hsweb.web.service.impl.DatabaseMetaDataFactoryBean;
 import org.hsweb.web.service.system.DataBaseManagerService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
 import org.springframework.stereotype.Service;
@@ -43,7 +45,7 @@ import java.util.Map;
  */
 @Service(value = "dataBaseManagerService")
 public class DataBaseManagerServiceImpl implements DataBaseManagerService {
-
+    private Logger logger = LoggerFactory.getLogger(this.getClass());
     @Resource
     private SqlExecutor sqlExecutor;