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
...@@ -5,16 +5,20 @@ import cn.hutool.core.util.ZipUtil; ...@@ -5,16 +5,20 @@ import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil; import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth; import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException; import com.mortals.framework.exception.AppException;
import com.mortals.xhx.base.system.upload.service.UploadService; import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.ProductDisEnum; import com.mortals.xhx.common.code.ProductDisEnum;
import com.mortals.xhx.common.code.ProjectDistributeEnum; 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.EncodeUtil;
import com.mortals.xhx.common.utils.ZipUtils; import com.mortals.xhx.common.utils.ZipUtils;
import com.mortals.xhx.module.setup.mode.ProjectSetupEntity; import com.mortals.xhx.module.setup.mode.ProjectSetupEntity;
import com.mortals.xhx.module.setup.mode.ResourceSetupEntity; import com.mortals.xhx.module.setup.mode.ResourceSetupEntity;
import com.mortals.xhx.module.setup.service.SetupProjectService;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; 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.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
...@@ -55,6 +59,9 @@ public class SetupProjectController { ...@@ -55,6 +59,9 @@ public class SetupProjectController {
@Autowired @Autowired
private UploadService uploadService; private UploadService uploadService;
@Autowired
private SetupProjectService setupProjectService;
@PostMapping("/init") @PostMapping("/init")
@UnAuth @UnAuth
public String initDb(@RequestBody ResourceSetupEntity resourceSetupEntity) { public String initDb(@RequestBody ResourceSetupEntity resourceSetupEntity) {
...@@ -104,11 +111,10 @@ public class SetupProjectController { ...@@ -104,11 +111,10 @@ public class SetupProjectController {
JSONObject ret = new JSONObject(); JSONObject ret = new JSONObject();
int code = VALUE_RESULT_SUCCESS; int code = VALUE_RESULT_SUCCESS;
try { try {
String unZipPath = publishPath; Rest<Void> rest = setupProjectService.distribute(projectSetupEntity);
String sourcePath = "/project/" + ProductDisEnum.getByValue(projectSetupEntity.getProjectValue()).getDesc() + "/" + projectSetupEntity.getProjectValue() + ".tar.gz"; if (rest.getCode() == YesNoEnum.YES.getValue()) {
InputStream inputStream = this.getClass().getResourceAsStream(sourcePath);
ZipUtils.unGzip(inputStream, unZipPath);
ret.put(KEY_RESULT_MSG, "项目资源部署成功"); ret.put(KEY_RESULT_MSG, "项目资源部署成功");
}
} catch (Exception e) { } catch (Exception e) {
code = VALUE_RESULT_FAILURE; code = VALUE_RESULT_FAILURE;
log.error("导入资源文件失败", e); log.error("导入资源文件失败", e);
......
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