Commit 85ff6d65 authored by 赵啸非's avatar 赵啸非

添加实例查询

parent fd361591
package com.mortals.xhx.module.setup.service;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.module.setup.mode.DbSetupEntity;
import org.aspectj.weaver.ast.Var;
import org.springframework.web.bind.annotation.RequestBody;
/**
* 资源部署
*
* @author: zxfei
* @date: 2024/9/20 10:31
*/
public interface SetupDbService {
/**
* 初始化db
* @param dbSetupEntity
* @return
*/
Rest<String> initDb( DbSetupEntity dbSetupEntity);
/**
* 测试数据库连接
* @param dbSetupEntity
* @return
*/
Rest<String> connect(DbSetupEntity dbSetupEntity);
}
\ No newline at end of file
package com.mortals.xhx.module.setup.service;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.module.setup.mode.ProjectSetupEntity;
import org.springframework.web.bind.annotation.RequestBody;
/**
* 项目安装服务
*
* @author: zxfei
* @date: 2024/9/20 10:31
*/
public interface SetupProjectService {
/**
* 项目部署
* @param projectSetupEntity
* @return
*/
Rest<Void> distribute(ProjectSetupEntity projectSetupEntity);
}
\ No newline at end of file
package com.mortals.xhx.module.setup.service;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.module.setup.mode.ProjectSetupEntity;
/**
* 资源部署
*
* @author: zxfei
* @date: 2024/9/20 10:31
*/
public interface SetupResourceService {
}
\ No newline at end of file
package com.mortals.xhx.module.setup.service.impl;
import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.proxy.jdbc.ConnectionProxy;
import com.alibaba.druid.util.JdbcUtils;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.module.setup.mode.DbSetupEntity;
import com.mortals.xhx.module.setup.service.SetupDbService;
import com.mortals.xhx.module.setup.service.SetupResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static com.mortals.framework.web.BaseController.KEY_RESULT_MSG;
import static com.mortals.framework.web.BaseController.VALUE_RESULT_FAILURE;
@Service("SetupProjectService")
@Slf4j
public class SetupDbServiceImpl implements SetupDbService {
@Value("${project.publishPath}")
private String publishPath;
@Autowired
private UploadService uploadService;
private int timeout = 5;
private String defaultValidateQuery = "SELECT 'x' FROM DUAL";
@Override
public Rest<String> initDb(DbSetupEntity dbSetupEntity) {
try {
//判断数据库是否已经存在 如果不存在 则链接默认库mysql 再初始化创建库
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUsername(dbSetupEntity.getUserName());
druidDataSource.setPassword(dbSetupEntity.getPassword());
DruidPooledConnection connection = druidDataSource.getConnection();
createDatabase(connection, dbSetupEntity.getDbName());
connection.setCatalog(dbSetupEntity.getDbName());
FileSystemResource rc = new FileSystemResource(uploadService.getFilePath(dbSetupEntity.getDbFilePath()));
EncodedResource er = new EncodedResource(rc, "UTF-8");
ScriptUtils.executeSqlScript(connection, er);
} catch (Exception e) {
return Rest.fail(e.getMessage());
}
return Rest.ok("初始化数据成功!");
}
@Override
public Rest<String> connect(DbSetupEntity dbSetupEntity) {
try {
SimpleDataSource simpleDataSource = new SimpleDataSource("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong"
, dbSetupEntity.getUserName(), dbSetupEntity.getPassword(), "com.mysql.cj.jdbc.Driver");
//判断数据库是否已经存在 如果不存在 则链接默认库mysql 再初始化创建库
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUsername(dbSetupEntity.getUserName());
druidDataSource.setPassword(dbSetupEntity.getPassword());
//druidDataSource.setConnectionErrorRetryAttempts(3); // 失败后重连的次数
druidDataSource.setBreakAfterAcquireFailure(true);
Connection connection = simpleDataSource.getConnection();
boolean databaseExists = databaseExists(connection, dbSetupEntity.getDbName());
if (!databaseExists) {
throw new AppException("数据库不存在");
}
boolean valid = isValidConnection(connection, null, 0);
if (valid) {
return Rest.ok("连接数据库成功!");
} else {
throw new AppException("连接数据库失败!");
}
} catch (Exception e) {
log.error("链接数据库异常", e);
return Rest.fail(e.getMessage());
}
}
//创建数据库
private boolean createDatabase(Connection conn, String dbName) throws SQLException {
// 检查数据库是否已经存在
if (!databaseExists(conn, dbName)) {
Statement stmt = conn.createStatement();
String sql = "CREATE DATABASE " + dbName + " default charset=utf8";
stmt.executeUpdate(sql);
log.info("成功创建数据库");
stmt.close();
return true;
}
log.info("数据库已经存在,无需创建与初始化");
return false;
}
//检查bank数据库是否存在
private boolean databaseExists(Connection conn, String dbName) throws SQLException {
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
if (dbName.equals(resultSet.getString(1))) {
return true;
}
}
return false;
}
//采用sql模式校验有效性
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
if (validateQuery == null || validateQuery.isEmpty()) {
validateQuery = this.defaultValidateQuery;
}
if (conn.isClosed()) {
return false;
}
if (conn instanceof DruidPooledConnection) {
conn = ((DruidPooledConnection) conn).getConnection();
}
if (conn instanceof ConnectionProxy) {
conn = ((ConnectionProxy) conn).getRawObject();
}
if (validateQuery == null || validateQuery.isEmpty()) {
return true;
}
int queryTimeout = validationQueryTimeout <= 0 ? timeout : validationQueryTimeout;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
stmt.setQueryTimeout(queryTimeout);
rs = stmt.executeQuery(validateQuery);
return true;
} catch (Exception e) {
throw new AppException(e.getMessage());
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(stmt);
}
}
}
\ No newline at end of file
package com.mortals.xhx.module.setup.service.impl;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.common.code.ProductDisEnum;
import com.mortals.xhx.common.utils.ZipUtils;
import com.mortals.xhx.module.setup.mode.ProjectSetupEntity;
import com.mortals.xhx.module.setup.service.SetupProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.InputStream;
@Service("SetupProjectService")
@Slf4j
public class SetupProjectServiceImpl implements SetupProjectService {
@Value("${project.publishPath}")
private String publishPath;
@Override
public Rest<Void> distribute(ProjectSetupEntity projectSetupEntity) {
String unZipPath = publishPath;
String sourcePath = "/project/" + ProductDisEnum.getByValue(projectSetupEntity.getProjectValue()).getDesc() + "/" + projectSetupEntity.getProjectValue() + ".tar.gz";
InputStream inputStream = this.getClass().getResourceAsStream(sourcePath);
ZipUtils.unGzip(inputStream, unZipPath);
return Rest.ok();
}
}
\ No newline at end of file
package com.mortals.xhx.module.setup.service.impl;
import com.mortals.xhx.module.setup.service.SetupResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service("SetupProjectService")
@Slf4j
public class SetupResourceServiceImpl implements SetupResourceService {
@Value("${project.publishPath}")
private String publishPath;
}
\ No newline at end of file
package com.mortals.xhx.module.setup.web;
import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.proxy.jdbc.ConnectionProxy;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.setup.mode.DbSetupEntity;
import com.mortals.xhx.module.setup.service.SetupDbService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static com.mortals.framework.web.BaseController.*;
......@@ -35,17 +24,7 @@ import static com.mortals.framework.web.BaseController.*;
public class SetupDbController {
@Autowired
private UploadService uploadService;
private int timeout = 1;
private String defaultValidateQuery = "SELECT 'x' FROM DUAL";
protected void init(Map<String, Object> model, Context context) {
// this.addDict(model, "product", ProductDisEnum.getEnumMap());
}
private SetupDbService setupDbService;
@PostMapping("/connect")
@UnAuth
......@@ -57,38 +36,12 @@ public class SetupDbController {
throw new AppException("请选择产品数据库名称");
}
SimpleDataSource simpleDataSource = new SimpleDataSource("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong"
,dbSetupEntity.getUserName(),dbSetupEntity.getPassword(),"com.mysql.cj.jdbc.Driver");
// simpleDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
// simpleDataSource.setDriver("com.mysql.cj.jdbc.Driver");
// simpleDataSource.setUser(dbSetupEntity.getUserName());
// simpleDataSource.setPass(dbSetupEntity.getPassword());
//判断数据库是否已经存在 如果不存在 则链接默认库mysql 再初始化创建库
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUsername(dbSetupEntity.getUserName());
druidDataSource.setPassword(dbSetupEntity.getPassword());
//druidDataSource.setConnectionErrorRetryAttempts(3); // 失败后重连的次数
druidDataSource.setBreakAfterAcquireFailure(true);
Connection connection = simpleDataSource.getConnection();
boolean valid = isValidConnection(connection, null, 0);
if (valid) {
Rest<String> rest = setupDbService.connect(dbSetupEntity);
if (YesNoEnum.YES.getValue() == rest.getCode()) {
ret.put(KEY_RESULT_MSG, "连接数据库成功!");
} else {
throw new AppException("连接数据库失败!");
throw new AppException(rest.getMsg());
}
boolean databaseExists = databaseExists(connection, dbSetupEntity.getDbName());
if (!databaseExists) {
throw new AppException("数据库不存在");
}
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("链接数据库异常", e);
......@@ -111,24 +64,12 @@ public class SetupDbController {
if (ObjectUtils.isEmpty(dbSetupEntity.getDbName())) {
throw new AppException("请输入数据库名称");
}
//判断数据库是否已经存在 如果不存在 则链接默认库mysql 再初始化创建库
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUsername(dbSetupEntity.getUserName());
druidDataSource.setPassword(dbSetupEntity.getPassword());
DruidPooledConnection connection = druidDataSource.getConnection();
createDatabase(connection, dbSetupEntity.getDbName());
connection.setCatalog(dbSetupEntity.getDbName());
FileSystemResource rc = new FileSystemResource(uploadService.getFilePath(dbSetupEntity.getDbFilePath()));
EncodedResource er = new EncodedResource(rc, "UTF-8");
ScriptUtils.executeSqlScript(connection, er);
ret.put(KEY_RESULT_MSG, "初始化数据库成功!");
Rest<String> rest = setupDbService.initDb(dbSetupEntity);
if (YesNoEnum.YES.getValue() == rest.getCode()) {
ret.put(KEY_RESULT_MSG, "初始化数据库成功!");
} else {
throw new AppException(rest.getMsg());
}
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("导入数据库失败", e);
......@@ -138,110 +79,4 @@ public class SetupDbController {
return ret.toJSONString();
}
/**
* 导入sql文件,生成库表数据
*
* @param file
* @return
*/
@PostMapping("/importDb")
@UnAuth
public String importDb(MultipartFile file, @RequestParam(required = false) Long appId) {
JSONObject ret = new JSONObject();
String busiDesc = "导入数据库";
int code = VALUE_RESULT_SUCCESS;
try {
//先链接已经存在的数据库
String filepath = uploadService.saveFileUpload(file, "/file/fileupload", null);
//CREATE DATABASE IF NOT EXISTS yourdbname DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDbType("com.alibaba.druid.pool.DruidDataSource");
druidDataSource.setUrl("jdbc:mysql://localhost:3306");
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUsername("root");
druidDataSource.setPassword("12345678");
DruidPooledConnection connection = druidDataSource.getConnection();
boolean xhx = databaseExists(connection, "base-platform");
log.info("xhx数据库是否存在:{}", xhx);
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("导入数据库失败", e);
//doException(request, busiDesc, model, e);
}
ret.put(KEY_RESULT_CODE, code);
return ret.toJSONString();
}
//检查bank数据库是否存在
private boolean databaseExists(Connection conn, String dbName) throws SQLException {
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
if (dbName.equals(resultSet.getString(1))) {
return true;
}
}
return false;
}
//创建数据库
private boolean createDatabase(Connection conn, String dbName) throws SQLException {
// 检查数据库是否已经存在
if (!databaseExists(conn, dbName)) {
Statement stmt = conn.createStatement();
String sql = "CREATE DATABASE " + dbName + " default charset=utf8";
stmt.executeUpdate(sql);
log.info("成功创建数据库");
stmt.close();
return true;
}
log.info("数据库已经存在,无需创建与初始化");
return false;
}
//采用sql模式校验有效性
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
if (validateQuery == null || validateQuery.isEmpty()) {
validateQuery = this.defaultValidateQuery;
}
if (conn.isClosed()) {
return false;
}
if (conn instanceof DruidPooledConnection) {
conn = ((DruidPooledConnection) conn).getConnection();
}
if (conn instanceof ConnectionProxy) {
conn = ((ConnectionProxy) conn).getRawObject();
}
if (validateQuery == null || validateQuery.isEmpty()) {
return true;
}
int queryTimeout = validationQueryTimeout <= 0 ? timeout : validationQueryTimeout;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
stmt.setQueryTimeout(queryTimeout);
rs = stmt.executeQuery(validateQuery);
return true;
} catch (Exception e) {
throw new AppException(e.getMessage());
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(stmt);
}
}
}
\ No newline at end of file
......@@ -5,16 +5,20 @@ import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.ProductDisEnum;
import com.mortals.xhx.common.code.ProjectDistributeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.utils.EncodeUtil;
import com.mortals.xhx.common.utils.ZipUtils;
import com.mortals.xhx.module.setup.mode.ProjectSetupEntity;
import com.mortals.xhx.module.setup.mode.ResourceSetupEntity;
import com.mortals.xhx.module.setup.service.SetupProjectService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
......@@ -55,6 +59,9 @@ public class SetupProjectController {
@Autowired
private UploadService uploadService;
@Autowired
private SetupProjectService setupProjectService;
@PostMapping("/init")
@UnAuth
public String initDb(@RequestBody ResourceSetupEntity resourceSetupEntity) {
......@@ -104,11 +111,10 @@ public class SetupProjectController {
JSONObject ret = new JSONObject();
int code = VALUE_RESULT_SUCCESS;
try {
String unZipPath = publishPath;
String sourcePath = "/project/" + ProductDisEnum.getByValue(projectSetupEntity.getProjectValue()).getDesc() + "/" + projectSetupEntity.getProjectValue() + ".tar.gz";
InputStream inputStream = this.getClass().getResourceAsStream(sourcePath);
ZipUtils.unGzip(inputStream, unZipPath);
ret.put(KEY_RESULT_MSG, "项目资源部署成功");
Rest<Void> rest = setupProjectService.distribute(projectSetupEntity);
if (rest.getCode() == YesNoEnum.YES.getValue()) {
ret.put(KEY_RESULT_MSG, "项目资源部署成功");
}
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("导入资源文件失败", e);
......@@ -159,7 +165,7 @@ public class SetupProjectController {
JSONObject ret = new JSONObject();
int code = VALUE_RESULT_SUCCESS;
try {
// curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/catalog/instances?serviceName=base-manager&clusterName=DEFAULT&groupName=DEFAULT_GROUP&pageSize=10&pageNo=1&namespaceId=smart-gov'
// curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/catalog/instances?serviceName=base-manager&clusterName=DEFAULT&groupName=DEFAULT_GROUP&pageSize=10&pageNo=1&namespaceId=smart-gov'
String resp = HttpUtil.get(nacosUrl + "/v1/ns/catalog/instances?serviceName=" + projectSetupEntity.getProjectValue() + "&clusterName=DEFAULT&groupName=DEFAULT_GROUP&pageSize=10&pageNo=1&namespaceId=smart-gov");
ret.put(KEY_RESULT_DATA, resp);
ret.put(KEY_RESULT_MSG, "服务实例详细查询成功");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment