编写测试连接的代码

master
冷调 2024-08-23 19:56:04 +08:00
parent fd2d3d2602
commit ad75e66218
10 changed files with 247 additions and 32 deletions

View File

@ -2,7 +2,13 @@
<profile version="1.0"> <profile version="1.0">
<option name="myName" value="Project Default" /> <option name="myName" value="Project Default" />
<inspection_tool class="AliAccessStaticViaInstance" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AliAccessStaticViaInstance" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliArrayNamingShouldHaveBracket" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliControlFlowStatementWithoutBraces" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliDeprecation" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AliDeprecation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliEqualsAvoidNull" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliLongLiteralsEndingWithLowercaseL" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliMissingOverrideAnnotation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AliWrapperTypeEquality" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAbstractClassShouldStartWithAbstractNaming" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AlibabaAbstractClassShouldStartWithAbstractNaming" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAbstractMethodOrInterfaceMethodMustUseJavadoc" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AlibabaAbstractMethodOrInterfaceMethodMustUseJavadoc" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidApacheBeanUtilsCopy" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AlibabaAvoidApacheBeanUtilsCopy" enabled="true" level="WARNING" enabled_by_default="true" />
@ -57,5 +63,6 @@
<inspection_tool class="AlibabaUnsupportedExceptionWithModifyAsList" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AlibabaUnsupportedExceptionWithModifyAsList" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaUseQuietReferenceNotation" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AlibabaUseQuietReferenceNotation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaUseRightCaseForDateFormat" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="AlibabaUseRightCaseForDateFormat" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="MapOrSetKeyShouldOverrideHashCodeEquals" enabled="true" level="WARNING" enabled_by_default="true" />
</profile> </profile>
</component> </component>

View File

@ -1,9 +1,12 @@
package com.muyu.config; package com.muyu.config;
import cn.hutool.core.math.Arrangement;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
import com.muyu.connection.DataSourceConfig;
import com.muyu.source.domain.Children; import com.muyu.source.domain.Children;
import com.muyu.source.domain.DataSource; import com.muyu.source.domain.DataSource;
import com.muyu.source.domain.DataType; import com.muyu.source.domain.DataType;
import com.muyu.source.domain.model.DataModel;
import com.muyu.source.remote.RemoteChildrenService; import com.muyu.source.remote.RemoteChildrenService;
import com.muyu.source.remote.RemoteDataSourceService; import com.muyu.source.remote.RemoteDataSourceService;
import com.muyu.source.remote.RemoteDataTypeService; import com.muyu.source.remote.RemoteDataTypeService;
@ -11,6 +14,9 @@ import jakarta.annotation.Resource;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import java.sql.*; import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** /**
* @author Lenovo * @author Lenovo
@ -22,48 +28,57 @@ import java.sql.*;
*/ */
@ComponentScan @ComponentScan
public class SourceClientConfig { public class SourceClientConfig {
@Resource
private RemoteDataTypeService remoteDataTypeService;
@Resource @Resource
private RemoteDataSourceService remoteDataSourceService; private RemoteDataSourceService remoteDataSourceService;
@Resource @Resource
private RemoteChildrenService remoteChildrenService; private RemoteChildrenService remoteChildrenService;
public void getDataModel(Long id){ public List<List<DataModel>> getDataModel(Long id) {
//根据ID查询出数据源的数据 List<List<DataModel>> list = new ArrayList<>();
Result<DataSource> dataSourceResult =remoteDataSourceService.getDataSource(id); //根据ID查询出表结构的数据
DataSource dataSource = dataSourceResult.getData(); Result<Children> childrenResult = remoteChildrenService.getChildren(id);
//根据ID查询出数据库类型的数据
Result<DataType> dataTypeResult = remoteDataTypeService.getDataType(dataSource.getDataType());
DataType dataType = dataTypeResult.getData();
//根据ID查询出数据源的数据库结构的数据
Result<Children> childrenResult =remoteChildrenService.getChildren(dataSource.getId());
Children children = childrenResult.getData(); Children children = childrenResult.getData();
//根据ID查询出数据源的数据
Result<DataSource> dataSourceResult = remoteDataSourceService.getDataSource(children.getAssetId());
try { DataSource dataSource = dataSourceResult.getData();
Class.forName(dataType.getDriverManager()); String sql = "";
} catch (ClassNotFoundException e) { if ("MySql".equals(dataSource.getDataType())) {
throw new RuntimeException(e); sql = "SELECT * FROM " + children.getName();
} }
try { try {
//获取连接对象 拼接数据库地址 //调用连接池获取连接
Connection connection = DriverManager.getConnection(dataType.getPrefix()+dataSource.getIp()+dataSource.getPort() Connection connection = DataSourceConfig.getDataSource(dataSource.getId());
+"//"+dataSource.getDatabaseName()+"?"+dataSource.getConnectionParam(),dataSource.getUserName(),dataSource.getPassword()); PreparedStatement preparedStatement = connection.prepareStatement(sql);
//创建执行对象 ResultSet resultSet = preparedStatement.executeQuery();
Statement statement = connection.createStatement(); ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
//拼接sql语句 while (resultSet.next()) {
ResultSet resultSet = statement.executeQuery("SELECT * FROM" + children.getName()); List<DataModel> dataModels = new ArrayList<>();
//处理返回结果 for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
while (resultSet.next()){ //获取列名 字段名 key
System.out.println(resultSet.getString(1)); String columnName = resultSetMetaData.getColumnName(i);
//获取字段的值 value
Object value = resultSet.getObject(columnName);
//获取列的类型 字段的类型 type
String columnTypeName = resultSetMetaData.getColumnTypeName(i);
//获取列的标题 label
String columnLabel = resultSetMetaData.getColumnLabel(i);
// java类型
String columnClassName = resultSetMetaData.getColumnClassName(i);
DataModel dataModel = DataModel.builder()
.key(columnName)
.label(columnLabel)
.type(columnTypeName)
.value(value)
.build();
dataModels.add(dataModel);
}
list.add(dataModels);
} }
//关闭资源 //归还连接
resultSet.close(); DataSourceConfig.returnConnection(connection);
statement.close();
connection.close();
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return list;
} }
} }

View File

@ -0,0 +1,45 @@
package com.muyu.config;
import com.muyu.common.core.domain.Result;
import com.muyu.connection.DataSourceConfig;
import com.muyu.source.domain.DataSource;
import com.muyu.source.domain.DataType;
import com.muyu.source.remote.RemoteChildrenService;
import com.muyu.source.remote.RemoteDataSourceService;
import com.muyu.source.remote.RemoteDataTypeService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @author Lenovo
* @ ToolIntelliJ IDEA
* @ AuthorCHX
* @ Date2024-08-23-9:45
* @ Version1.0
* @ Description
*/
@Log4j2
@Configuration
public class SourceClientRunner implements ApplicationRunner {
@Resource
private RemoteDataSourceService remoteDataSourceService;
@Resource
private RemoteDataTypeService remoteDataTypeService;
@Override
public void run(ApplicationArguments args) throws Exception {
Result<List<DataSource>> sourceResult = remoteDataSourceService.getDataSourceList();
log.info(sourceResult);
List<DataSource> sourceList = sourceResult.getData();
sourceList.stream().forEach(source -> {
Result<DataType> dataTypeResult = remoteDataTypeService.getDataType(source.getDataType());
DataType dataType = dataTypeResult.getData();
DataSourceConfig.init(source, dataType);
});
}
}

View File

@ -0,0 +1,39 @@
package com.muyu.source.domain.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
/**
* @author Lenovo
* @ ToolIntelliJ IDEA
* @ AuthorCHX
* @ Date2024-08-23-9:41
* @ Version1.0
* @ Description
*/
@Data
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class DataModel {
/**
*
*/
private String key;
/**
*
*/
private String label;
/**
*
*/
private String type;
/**
*
*/
private Object value;
}

View File

@ -8,6 +8,8 @@ import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/** /**
* @author Lenovo * @author Lenovo
* @ ToolIntelliJ IDEA * @ ToolIntelliJ IDEA
@ -23,4 +25,7 @@ public interface RemoteDataSourceService {
@GetMapping("/getDataSourceById/{id}") @GetMapping("/getDataSourceById/{id}")
Result<DataSource> getDataSource(@PathVariable Long id); Result<DataSource> getDataSource(@PathVariable Long id);
@GetMapping("/getDataSourceList")
Result<List<DataSource>> getDataSourceList();
} }

View File

@ -5,6 +5,8 @@ import com.muyu.source.domain.DataSource;
import com.muyu.source.remote.RemoteDataSourceService; import com.muyu.source.remote.RemoteDataSourceService;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import java.util.List;
/** /**
* @author Lenovo * @author Lenovo
* @ ToolIntelliJ IDEA * @ ToolIntelliJ IDEA
@ -21,6 +23,11 @@ public class RemoteDataSourceFactory implements FallbackFactory<RemoteDataSource
public Result<DataSource> getDataSource(Long id) { public Result<DataSource> getDataSource(Long id) {
return Result.error(cause.getMessage()); return Result.error(cause.getMessage());
} }
@Override
public Result<List<DataSource>> getDataSourceList() {
return Result.error(cause.getMessage());
}
}; };
} }
} }

View File

@ -1,5 +1,7 @@
package com.muyu.source.controller; package com.muyu.source.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dtflys.forest.springboot.annotation.ForestScannerRegister; import com.dtflys.forest.springboot.annotation.ForestScannerRegister;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.poi.ExcelUtil; import com.muyu.common.core.utils.poi.ExcelUtil;
@ -45,6 +47,36 @@ public class DataSourceController extends BaseController {
@Autowired @Autowired
private DataSourceService dataSourceService; private DataSourceService dataSourceService;
/**
*
* @param dataSource
* @return
*/
@PostMapping("/test")
public Result testConnection(@RequestBody DataSource dataSource){
Boolean b =dataSourceService.testConnection(dataSource);
if(b){
dataSourceService.update(new LambdaUpdateWrapper<>() {{
set(DataSource::getIsInit, "Y");
eq(DataSource::getId, dataSource.getId());
}});
return Result.success(b,"连接成功");
}
return Result.error("连接失败");
}
/**
*
* @return
*/
@GetMapping("/getDataSourceList")
public Result<List<DataSource>> getDataSourceList(){
List<DataSource> dataSourceList =dataSourceService.list();
return success(dataSourceList);
}
/** /**
* *
*/ */

View File

@ -39,5 +39,5 @@ public interface DataSourceService extends IService<DataSource> {
Boolean checkIdUnique(DataSource dataSource); Boolean checkIdUnique(DataSource dataSource);
Boolean testConnection(DataSource dataSource);
} }

View File

@ -0,0 +1,14 @@
package com.muyu.source.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.muyu.source.domain.DataType;
/**
* @ ToolIntelliJ IDEA
* @ AuthorCHX
* @ Date2024-08-23-18:59
* @ Version1.0
* @ Description
*/
public interface DataTypeService extends IService<DataType> {
}

View File

@ -5,11 +5,18 @@ import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.common.core.utils.StringUtils; import com.muyu.common.core.utils.StringUtils;
import com.muyu.source.domain.DataSource; import com.muyu.source.domain.DataSource;
import com.muyu.source.domain.DataType;
import com.muyu.source.mapper.DataSourceMapper; import com.muyu.source.mapper.DataSourceMapper;
import com.muyu.source.service.DataSourceService; import com.muyu.source.service.DataSourceService;
import com.muyu.source.service.DataTypeService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService;
import static java.util.concurrent.Executors.newFixedThreadPool;
/** /**
* @author Lenovo * @author Lenovo
@ -22,6 +29,10 @@ import java.util.List;
@Service @Service
public class DataSourceServiceImpl extends ServiceImpl<DataSourceMapper, DataSource> implements DataSourceService { public class DataSourceServiceImpl extends ServiceImpl<DataSourceMapper, DataSource> implements DataSourceService {
@Resource
private DataTypeService dataTypeService;
private final ExecutorService executor = newFixedThreadPool(10);
/** /**
* *
@ -79,5 +90,45 @@ public class DataSourceServiceImpl extends ServiceImpl<DataSourceMapper, DataSou
return this.count(queryWrapper) > 0; return this.count(queryWrapper) > 0;
} }
/**
*
* @param dataSource
* @return
*/
@Override
public Boolean testConnection(DataSource dataSource) {
DataType dataType = dataTypeService.getOne(new LambdaQueryWrapper<>() {{
eq(DataType::getType, dataSource.getDataType());
}});
//
String jdbcUrl="";
boolean flag=false;
try{
//判空
if(dataType.getDriverManager()!=null && dataType.getPrefix()!=null){
if("MySql".equals(dataType.getType())){
//mysql拼接连接路径
jdbcUrl=dataType.getDriverManager()+dataType.getPrefix()+dataSource.getIp()+":"+dataSource.getPort()+"/"+dataSource.getDatabaseName()+"?"+dataSource.getConnectionParam();
}
flag=testConnection(dataType.getDriverManager(),jdbcUrl,dataSource.getUserName(),dataSource.getPassword());
}
return flag;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
private boolean testConnection(String driverManager, String jdbcUrl, String userName, String password) {
if(StringUtils.isNotEmpty(driverManager) && StringUtils.isNotEmpty(jdbcUrl) && StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)){
try{
Class.forName(driverManager);
return true;
}catch (Exception e){
e.printStackTrace();
}
}
return false;
}
} }