任务管理页面优化

This commit is contained in:
lizemin
2024-04-22 18:36:47 +08:00
parent 18972f3c4e
commit 3dd26e183c
9 changed files with 623 additions and 288 deletions

View File

@@ -2,18 +2,19 @@
<div>
<el-card>
<el-row>
<el-button size="mini" icon="el-icon-switch-button" :disabled=false plain>启动</el-button>
<el-button size="mini" icon="el-icon-video-pause" :disabled=true plain>停止</el-button>
<el-button size="mini" icon="el-icon-switch-button" :disabled=isSelected plain @click="batchStart()">启动
</el-button>
<el-button size="mini" icon="el-icon-video-pause" :disabled=isSelected plain @click="batchStop()">停止</el-button>
<span style="color:#e9e9f3;">&nbsp;&nbsp;|&nbsp;&nbsp;</span>
<el-button size="mini" plain>导入任务</el-button>
<el-button size="mini" :disabled=true plain>导出任务</el-button>
<!-- <div class="right-add-button-group">-->
<el-button class="right-add-button-group" type="primary"
size="mini"
icon="el-icon-document-add"
@click="handleCreate">创建任务
</el-button>
<!-- </div>-->
<el-button size="mini" :disabled=isSelected plain @click="batchExport()">导出任务</el-button>
<!-- <div class="right-add-button-group">-->
<el-button class="right-add-button-group" type="primary"
size="mini"
icon="el-icon-document-add"
@click="handleCreate">创建任务
</el-button>
<!-- </div>-->
</el-row>
<div class="assignment-list-top">
<div class="left-search-input-group">
@@ -33,7 +34,8 @@
<el-table :header-cell-style="{background:'#eef1f6',color:'#606266'}"
:data="tableData"
size="small"
border>
border
@selection-change="handleSelectionChange">
<el-table-column prop="id"
label="编号"
type="selection"
@@ -81,7 +83,8 @@
<el-icon class="el-icon-success color-success" v-if="scope.row.runStatus == '执行成功'"></el-icon>
<el-icon class="el-icon-error color-error" v-if="scope.row.runStatus == '执行异常'"></el-icon>
<el-icon class="el-icon-remove color-cancel" v-if="scope.row.runStatus == '任务取消'"></el-icon>
<el-icon class="el-icon-loading color-running" v-if="scope.row.runStatus == '执行中'"></el-icon>
<el-icon class="el-icon-video-play color-running" v-if="scope.row.runStatus == '执行中'"></el-icon>
<el-icon class="el-icon-loading color-await" v-if="scope.row.runStatus == '待执行'"></el-icon>
<span>{{ scope.row.runStatus }}</span>
</template>
</el-table-column>
@@ -172,6 +175,8 @@ export default {
totalCount: 2,
keyword: null,
tableData: [],
isSelected: true,
idsSelected:[]
};
},
methods: {
@@ -220,11 +225,120 @@ export default {
return "定时";
}
},
stringSourceSchema(row, column) {
return row.sourceSchema + " / " + row.sourceType
handleSelectionChange(val) {
if (val.length > 0) {
this.isSelected = false;
this.idsSelected.push(val.map(item => item.id));
}else {
this.isSelected = true;
this.idsSelected = []
}
},
stringTargetSchema(row, column) {
return row.targetSchema + " / " + row.targetType
batchStart(){
console.log(this.idsSelected)
this.$http({
method: "POST",
headers: {
'Content-Type': 'application/json'
},
url: "/dbswitch/admin/api/v1/assignment/deploy?ids=" + this.idsSelected,
}).then(res => {
if (0 === res.data.code) {
this.$message({
message: '任务发布成功!',
type: 'success'
});
this.loadData();
} else {
if (res.data.message) {
this.$message.error("任务发布失败," + res.data.message);
}
}
});
},
batchStop(){
this.$http({
method: "POST",
headers: {
'Content-Type': 'application/json'
},
url: "/dbswitch/admin/api/v1/assignment/retire?ids=" + this.idsSelected,
}).then(res => {
if (0 === res.data.code) {
this.$message({
message: '下线任务成功!',
type: 'success'
});
this.loadData();
} else {
if (res.data.message) {
this.$message.error("下线任务失败," + res.data.message);
}
}
});
},
batchExport(){
this.$http({
method: "POST",
headers: {
'Content-Type': 'application/json'
},
url: "/dbswitch/admin/api/v1/assignment/export?ids=" + this.idsSelected,
responseType: 'blob',
}).then(res => {
debugger
if (200 === res.status) {
this.downloadFile(res)
this.$message({
message: '导出任务成功!',
type: 'success'
});
this.loadData();
} else {
if (res.data.message) {
this.$message.error("导出任务失败," + res.data.message);
}
}
});
},
downloadFile: function (resp) {
const headers = resp.headers;
const contentType = headers['content-type'];
if (!resp.data) {
console.error('响应异常:', resp);
return false;
} else {
console.info('下载文件:', resp);
const blob = new Blob([resp.data], {
type: contentType
});
const contentDisposition = resp.headers['Content-disposition'];
let fileName = 'unknown';
if (contentDisposition) {
debugger
fileName = window.decodeURI(resp.headers['Content-disposition'].split('=')[1]);
}
console.log('文件名称:', fileName);
this.downFile(blob, fileName);
}
},
/* 下载方法 : 根据blob下载 */
downFile: function (blob, fileName) {
// 非IE下载
if ('download' in document.createElement('a')) {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob); // 创建下载的链接
link.download = fileName; // 下载后文件名
link.style.display = 'none';
document.body.appendChild(link);
link.click(); // 点击下载
window.URL.revokeObjectURL(link.href); // 释放掉blob对象
document.body.removeChild(link); // 下载完成移除元素
} else {
// IE10+下载
window.navigator.msSaveBlob(blob, fileName);
}
},
handleCreate: function () {
this.$router.push('/task/create')
@@ -267,11 +381,14 @@ export default {
url: "/dbswitch/admin/api/v1/assignment/deploy?ids=" + row.id,
}).then(res => {
if (0 === res.data.code) {
this.$message("任务发布成功");
this.$message({
message: '任务发布成功!',
type: 'success'
});
this.loadData();
} else {
if (res.data.message) {
alert("任务发布失败," + res.data.message);
this.$message.error("任务发布失败," + res.data.message);
}
}
});
@@ -286,11 +403,14 @@ export default {
data: JSON.stringify([row.id])
}).then(res => {
if (0 === res.data.code) {
this.$message("手动启动执行任务成功");
this.$message({
message: '手动启动执行任务成功!',
type: 'success'
});
this.loadData();
} else {
if (res.data.message) {
alert("手动启动执行任务失败," + res.data.message);
this.$message.error("手动启动执行任务失败," + res.data.message);
}
}
});
@@ -304,11 +424,14 @@ export default {
url: "/dbswitch/admin/api/v1/assignment/retire?ids=" + row.id,
}).then(res => {
if (0 === res.data.code) {
this.$message("下线任务成功");
this.$message({
message: '下线任务成功!',
type: 'success'
});
this.loadData();
} else {
if (res.data.message) {
alert("下线任务失败," + res.data.message);
this.$message.error("下线任务失败," + res.data.message);
}
}
});
@@ -392,12 +515,16 @@ export default {
.right-add-button-group {
width: 100px;
margin-left: auto;
//margin: 0px 0px;
/ / margin: 0 px 0 px;
float: right;
}
.color-await {
color: #a0a6b8 !important;
}
.color-running {
color: #8c85d1 !important;
color: #6cdbbc !important;
}
.color-error {
@@ -412,7 +539,7 @@ export default {
color: #6cdbbc !important;
}
.btn-common{
.btn-common {
}

View File

@@ -113,6 +113,16 @@
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>

View File

@@ -0,0 +1,30 @@
package com.gitee.dbswitch.admin.controller.converter;
import com.gitee.dbswitch.admin.entity.AssignmentTaskEntity;
import com.gitee.dbswitch.admin.model.response.AssignmentsDataResponse;
import com.gitee.dbswitch.common.converter.AbstractConverter;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
/**
* @author Li Zemin
* @since 2024/4/22 9:44
*/
public class AssignmentsConverter extends
AbstractConverter<AssignmentTaskEntity, AssignmentsDataResponse> {
@Override
public AssignmentsDataResponse convert(AssignmentTaskEntity assignmentTaskEntity) {
AssignmentsDataResponse response = new AssignmentsDataResponse();
response.setId(assignmentTaskEntity.getId());
response.setName(assignmentTaskEntity.getName());
response.setDescription(assignmentTaskEntity.getDescription());
response.setScheduleMode(assignmentTaskEntity.getScheduleMode().getName());
response.setCronExpression(assignmentTaskEntity.getCronExpression());
response.setIsPublished(assignmentTaskEntity.getPublished());
response.setCreateTime(DateUtil.format(assignmentTaskEntity.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
response.setUpdateTime(DateUtil.format(assignmentTaskEntity.getUpdateTime(), DatePattern.NORM_DATETIME_PATTERN));
return response;
}
}

View File

@@ -24,6 +24,8 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@@ -112,4 +114,12 @@ public class AssignmentController {
return Result.success();
}
@TokenCheck
@LogOperate(name = "导出任务", description = "'导出任务的ID为'+#ids")
@ApiOperation(value = "导出")
@PostMapping(value = "/export")
public void exportAssignments(@RequestParam(value = "ids") List<Long> ids, HttpServletResponse response) {
assignmentService.exportAssignments(ids,response);
}
}

View File

@@ -0,0 +1,13 @@
package com.gitee.dbswitch.admin.convert;
import com.gitee.dbswitch.admin.entity.AssignmentTaskEntity;
import com.gitee.dbswitch.admin.model.response.AssignmentsDataResponse;
/**
* @author Li Zemin
* @since 2024/4/22 9:44
*/
//@Mapper
public interface AssignmentConvert {
AssignmentsDataResponse toAssignmentsDataResponse(AssignmentTaskEntity assignmentTaskEntity);
}

View File

@@ -0,0 +1,67 @@
package com.gitee.dbswitch.admin.model.response;
import java.sql.Timestamp;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.gitee.dbswitch.admin.type.ScheduleModeEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class AssignmentsDataResponse {
@ExcelProperty("ID编号")
private Long id;
@ExcelProperty("任务名")
private String name;
@ExcelProperty("描述")
private String description;
@ExcelProperty("调度模式")
private String scheduleMode;
@ExcelProperty("Cron表达式")
private String cronExpression;
@ExcelProperty("是否已发布")
private Boolean isPublished;
@ExcelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private String createTime;
@ExcelProperty("更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private String updateTime;
@ExcelProperty("源端数据源")
private String sourceSchema;
@ExcelProperty("源端数据源类型")
private String sourceType;
@ExcelProperty("目标端数据源")
private String targetSchema;
@ExcelProperty("目标端数据源类型")
private String targetType;
@ExcelProperty("运行状态")
private String runStatus;
}

View File

@@ -9,6 +9,23 @@
/////////////////////////////////////////////////////////////
package com.gitee.dbswitch.admin.service;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gitee.dbswitch.admin.common.exception.DbswitchException;
import com.gitee.dbswitch.admin.common.response.PageResult;
@@ -16,6 +33,7 @@ import com.gitee.dbswitch.admin.common.response.Result;
import com.gitee.dbswitch.admin.common.response.ResultCode;
import com.gitee.dbswitch.admin.controller.converter.AssignmentDetailConverter;
import com.gitee.dbswitch.admin.controller.converter.AssignmentInfoConverter;
import com.gitee.dbswitch.admin.controller.converter.AssignmentsConverter;
import com.gitee.dbswitch.admin.dao.AssignmentConfigDAO;
import com.gitee.dbswitch.admin.dao.AssignmentTaskDAO;
import com.gitee.dbswitch.admin.dao.DatabaseConnectionDAO;
@@ -29,6 +47,7 @@ import com.gitee.dbswitch.admin.model.request.AssigmentUpdateRequest;
import com.gitee.dbswitch.admin.model.request.AssignmentSearchRequest;
import com.gitee.dbswitch.admin.model.response.AssignmentDetailResponse;
import com.gitee.dbswitch.admin.model.response.AssignmentInfoResponse;
import com.gitee.dbswitch.admin.model.response.AssignmentsDataResponse;
import com.gitee.dbswitch.admin.type.JobStatusEnum;
import com.gitee.dbswitch.admin.type.ScheduleModeEnum;
import com.gitee.dbswitch.admin.util.PageUtils;
@@ -39,309 +58,356 @@ import com.gitee.dbswitch.data.entity.GlobalParamConfigProperties;
import com.gitee.dbswitch.data.entity.SourceDataSourceProperties;
import com.gitee.dbswitch.data.entity.TargetDataSourceProperties;
import com.gitee.dbswitch.data.util.JsonUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AssignmentService {
@Resource
private AssignmentTaskDAO assignmentTaskDAO;
@Resource
private AssignmentTaskDAO assignmentTaskDAO;
@Resource
private AssignmentConfigDAO assignmentConfigDAO;
@Resource
private AssignmentConfigDAO assignmentConfigDAO;
@Resource
private ScheduleService scheduleService;
@Resource
private ScheduleService scheduleService;
@Resource
private DatabaseConnectionDAO databaseConnectionDAO;
@Resource
private DatabaseConnectionDAO databaseConnectionDAO;
@Resource
private DriverLoadService driverLoadService;
@Resource
private DriverLoadService driverLoadService;
@Resource
private AssignmentJobMapper assignmentJobMapper;
@Resource
private AssignmentJobMapper assignmentJobMapper;
@Transactional(rollbackFor = Exception.class)
public AssignmentInfoResponse createAssignment(AssigmentCreateRequest request) {
AssignmentTaskEntity assignment = request.toAssignmentTask();
assignmentTaskDAO.insert(assignment);
// @Resource
// private AssignmentConvert assignmentConvert;
AssignmentConfigEntity assignmentConfigEntity = request.toAssignmentConfig(assignment.getId());
assignmentConfigDAO.insert(assignmentConfigEntity);
@Transactional(rollbackFor = Exception.class)
public AssignmentInfoResponse createAssignment(AssigmentCreateRequest request) {
AssignmentTaskEntity assignment = request.toAssignmentTask();
assignmentTaskDAO.insert(assignment);
Long targetConnectionId = assignmentConfigEntity.getTargetConnectionId();
DatabaseConnectionEntity targetEntity = databaseConnectionDAO.getById(targetConnectionId);
if (ProductTypeEnum.SQLITE3 == targetEntity.getType()) {
if (ProductTypeEnum.isUnsupportedTargetSqlite(targetEntity.getUrl())) {
throw new DbswitchException(ResultCode.ERROR_INVALID_ASSIGNMENT_CONFIG,
"不支持目的端数据源为远程服务器上的SQLite或内存方式下的SQLite");
}
}
AssignmentConfigEntity assignmentConfigEntity = request.toAssignmentConfig(assignment.getId());
assignmentConfigDAO.insert(assignmentConfigEntity);
Long sourceConnectionId = assignmentConfigEntity.getSourceConnectionId();
DatabaseConnectionEntity sourceEntity = databaseConnectionDAO.getById(sourceConnectionId);
if (ProductTypeEnum.ELASTICSEARCH == sourceEntity.getType()) {
throw new DbswitchException(ResultCode.ERROR_INVALID_ASSIGNMENT_CONFIG,
"不支持源端数据源为ElasticSearch类型");
}
Long targetConnectionId = assignmentConfigEntity.getTargetConnectionId();
DatabaseConnectionEntity targetEntity = databaseConnectionDAO.getById(targetConnectionId);
if (ProductTypeEnum.SQLITE3 == targetEntity.getType()) {
if (ProductTypeEnum.isUnsupportedTargetSqlite(targetEntity.getUrl())) {
throw new DbswitchException(ResultCode.ERROR_INVALID_ASSIGNMENT_CONFIG,
"不支持目的端数据源为远程服务器上的SQLite或内存方式下的SQLite");
}
}
return ConverterFactory.getConverter(AssignmentInfoConverter.class)
.convert(assignmentTaskDAO.getById(assignment.getId()));
}
Long sourceConnectionId = assignmentConfigEntity.getSourceConnectionId();
DatabaseConnectionEntity sourceEntity = databaseConnectionDAO.getById(sourceConnectionId);
if (ProductTypeEnum.ELASTICSEARCH == sourceEntity.getType()) {
throw new DbswitchException(ResultCode.ERROR_INVALID_ASSIGNMENT_CONFIG,
"不支持源端数据源为ElasticSearch类型");
}
public void deleteAssignment(Long id) {
AssignmentTaskEntity taskEntity = assignmentTaskDAO.getById(id);
if (null != taskEntity && null != taskEntity.getPublished() && taskEntity.getPublished()) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_HAS_DEPLOY,
"已经发布的任务需先下线后方可执行删除操作");
}
assignmentTaskDAO.deleteById(id);
}
return ConverterFactory.getConverter(AssignmentInfoConverter.class)
.convert(assignmentTaskDAO.getById(assignment.getId()));
}
@Transactional(rollbackFor = Exception.class)
public void updateAssignment(AssigmentUpdateRequest request) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(request.getId());
if (Objects.isNull(assignmentTaskEntity)) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_NOT_EXISTS, "ID=" + request.getId());
} else if (assignmentTaskEntity.getPublished()) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_HAS_DEPLOY, "ID=" + request.getId());
}
public void deleteAssignment(Long id) {
AssignmentTaskEntity taskEntity = assignmentTaskDAO.getById(id);
if (null != taskEntity && null != taskEntity.getPublished() && taskEntity.getPublished()) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_HAS_DEPLOY,
"已经发布的任务需先下线后方可执行删除操作");
}
assignmentTaskDAO.deleteById(id);
}
AssignmentTaskEntity newAssignmentTaskEntity = request.toAssignmentTask();
assignmentTaskDAO.updateById(newAssignmentTaskEntity);
@Transactional(rollbackFor = Exception.class)
public void updateAssignment(AssigmentUpdateRequest request) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(request.getId());
if (Objects.isNull(assignmentTaskEntity)) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_NOT_EXISTS, "ID=" + request.getId());
} else if (assignmentTaskEntity.getPublished()) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_HAS_DEPLOY, "ID=" + request.getId());
}
AssignmentConfigEntity assignmentConfigEntity = request
.toAssignmentConfig(assignmentTaskEntity.getId());
assignmentConfigDAO.deleteByAssignmentTaskId(assignmentTaskEntity.getId());
assignmentConfigDAO.insert(assignmentConfigEntity);
AssignmentTaskEntity newAssignmentTaskEntity = request.toAssignmentTask();
assignmentTaskDAO.updateById(newAssignmentTaskEntity);
Long targetConnectionId = assignmentConfigEntity.getTargetConnectionId();
DatabaseConnectionEntity entity = databaseConnectionDAO.getById(targetConnectionId);
if (ProductTypeEnum.SQLITE3 == entity.getType()) {
if (ProductTypeEnum.isUnsupportedTargetSqlite(entity.getUrl())) {
throw new DbswitchException(ResultCode.ERROR_INVALID_ASSIGNMENT_CONFIG,
"不支持目的端数据源为远程服务器上的SQLite或内存方式下的SQLite");
}
}
}
AssignmentConfigEntity assignmentConfigEntity = request
.toAssignmentConfig(assignmentTaskEntity.getId());
assignmentConfigDAO.deleteByAssignmentTaskId(assignmentTaskEntity.getId());
assignmentConfigDAO.insert(assignmentConfigEntity);
public PageResult<AssignmentInfoResponse> listAll(AssignmentSearchRequest request) {
Supplier<List<AssignmentInfoResponse>> method = () -> {
List<AssignmentInfoResponse> assignmentInfoResponseList = ConverterFactory.getConverter(AssignmentInfoConverter.class)
.convert(assignmentTaskDAO.listAll(request.getSearchText()));
assignmentInfoResponseList.forEach((e)->{
AssignmentConfigEntity assignmentConfigEntity = this.assignmentConfigDAO.getByAssignmentTaskId(e.getId());
Long targetConnectionId = assignmentConfigEntity.getTargetConnectionId();
DatabaseConnectionEntity entity = databaseConnectionDAO.getById(targetConnectionId);
if (ProductTypeEnum.SQLITE3 == entity.getType()) {
if (ProductTypeEnum.isUnsupportedTargetSqlite(entity.getUrl())) {
throw new DbswitchException(ResultCode.ERROR_INVALID_ASSIGNMENT_CONFIG,
"不支持目的端数据源为远程服务器上的SQLite或内存方式下的SQLite");
}
}
}
Long sourceConnectionId = assignmentConfigEntity.getSourceConnectionId();
DatabaseConnectionEntity databaseConnectionEntity = this.databaseConnectionDAO.getById(sourceConnectionId);
String sourceSchema = assignmentConfigEntity.getSourceSchema();
e.setSourceSchema(sourceSchema);
String sourceType = databaseConnectionEntity.getType().getName();
e.setSourceType(sourceType);
public PageResult<AssignmentInfoResponse> listAll(AssignmentSearchRequest request) {
Supplier<List<AssignmentInfoResponse>> method = () -> {
List<AssignmentInfoResponse> assignmentInfoResponseList = ConverterFactory.getConverter(AssignmentInfoConverter.class)
.convert(assignmentTaskDAO.listAll(request.getSearchText()));
assignmentInfoResponseList.forEach((e) -> {
AssignmentConfigEntity assignmentConfigEntity = this.assignmentConfigDAO.getByAssignmentTaskId(e.getId());
Long targetConnectionId = assignmentConfigEntity.getTargetConnectionId();
DatabaseConnectionEntity databaseConnectionEntity1 = this.databaseConnectionDAO.getById(targetConnectionId);
String targetSchema = assignmentConfigEntity.getTargetSchema();
e.setTargetSchema(targetSchema);
String targetType = databaseConnectionEntity1.getType().getName();
e.setTargetType(targetType);
Long sourceConnectionId = assignmentConfigEntity.getSourceConnectionId();
DatabaseConnectionEntity databaseConnectionEntity = this.databaseConnectionDAO.getById(sourceConnectionId);
String sourceSchema = assignmentConfigEntity.getSourceSchema();
e.setSourceSchema(sourceSchema);
String sourceType = databaseConnectionEntity.getType().getName();
e.setSourceType(sourceType);
AssignmentJobEntity assignmentJobEntity = this.assignmentJobMapper.selectOne(
new LambdaQueryWrapper<AssignmentJobEntity>()
.eq(AssignmentJobEntity::getAssignmentId, e.getId()).orderByDesc(AssignmentJobEntity::getCreateTime)
.last(" limit 1 "));
Integer status = (assignmentJobEntity == null || assignmentJobEntity.getStatus() == null) ?
JobStatusEnum.INIT.getValue() :
assignmentJobEntity.getStatus();
e.setRunStatus(JobStatusEnum.of(status).getName());
Long targetConnectionId = assignmentConfigEntity.getTargetConnectionId();
DatabaseConnectionEntity databaseConnectionEntity1 = this.databaseConnectionDAO.getById(targetConnectionId);
String targetSchema = assignmentConfigEntity.getTargetSchema();
e.setTargetSchema(targetSchema);
String targetType = databaseConnectionEntity1.getType().getName();
e.setTargetType(targetType);
});
return assignmentInfoResponseList;
};
return PageUtils.getPage(method, request.getPage(), request.getSize());
}
AssignmentJobEntity assignmentJobEntity = this.assignmentJobMapper.selectOne(
new LambdaQueryWrapper<AssignmentJobEntity>()
.eq(AssignmentJobEntity::getAssignmentId, e.getId()).orderByDesc(AssignmentJobEntity::getCreateTime)
.last(" limit 1 "));
Integer status = (assignmentJobEntity == null || assignmentJobEntity.getStatus() == null) ?
JobStatusEnum.INIT.getValue() :
assignmentJobEntity.getStatus();
e.setRunStatus(JobStatusEnum.of(status).getName());
public Result<AssignmentDetailResponse> detailAssignment(Long id) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (Objects.isNull(assignmentTaskEntity)) {
return Result.failed(ResultCode.ERROR_RESOURCE_NOT_EXISTS, "ID=" + id);
}
});
return assignmentInfoResponseList;
};
return PageUtils.getPage(method, request.getPage(), request.getSize());
}
AssignmentDetailResponse detailResponse = ConverterFactory
.getConverter(AssignmentDetailConverter.class).convert(assignmentTaskEntity);
return Result.success(detailResponse);
}
public Result<AssignmentDetailResponse> detailAssignment(Long id) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (Objects.isNull(assignmentTaskEntity)) {
return Result.failed(ResultCode.ERROR_RESOURCE_NOT_EXISTS, "ID=" + id);
}
@Transactional(rollbackFor = Exception.class)
public void deployAssignments(List<Long> ids) {
checkAssignmentAllExist(ids);
ids.forEach(id -> {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (assignmentTaskEntity.getPublished()) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_HAS_DEPLOY, "ID=" + id);
}
});
AssignmentDetailResponse detailResponse = ConverterFactory
.getConverter(AssignmentDetailConverter.class).convert(assignmentTaskEntity);
return Result.success(detailResponse);
}
for (Long id : ids) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
AssignmentConfigEntity assignmentConfigEntity = assignmentConfigDAO.getByAssignmentTaskId(id);
@Transactional(rollbackFor = Exception.class)
public void deployAssignments(List<Long> ids) {
checkAssignmentAllExist(ids);
ids.forEach(id -> {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (assignmentTaskEntity.getPublished()) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_HAS_DEPLOY, "ID=" + id);
}
});
DbswichPropertiesConfiguration properties = new DbswichPropertiesConfiguration();
properties.setSource(this.getSourceDataSourceProperties(assignmentConfigEntity));
properties.setTarget(this.getTargetDataSourceProperties(assignmentConfigEntity));
properties.setConfig(this.getGlobalParamConfigProperties(assignmentConfigEntity));
for (Long id : ids) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
AssignmentConfigEntity assignmentConfigEntity = assignmentConfigDAO.getByAssignmentTaskId(id);
assignmentTaskEntity.setPublished(Boolean.TRUE);
assignmentTaskEntity.setContent(JsonUtils.toJsonString(properties));
assignmentTaskDAO.updateById(assignmentTaskEntity);
DbswichPropertiesConfiguration properties = new DbswichPropertiesConfiguration();
properties.setSource(this.getSourceDataSourceProperties(assignmentConfigEntity));
properties.setTarget(this.getTargetDataSourceProperties(assignmentConfigEntity));
properties.setConfig(this.getGlobalParamConfigProperties(assignmentConfigEntity));
ScheduleModeEnum systemScheduled = ScheduleModeEnum.SYSTEM_SCHEDULED;
if (assignmentTaskEntity.getScheduleMode() == systemScheduled) {
scheduleService.scheduleTask(assignmentTaskEntity.getId(), systemScheduled);
}
}
assignmentTaskEntity.setPublished(Boolean.TRUE);
assignmentTaskEntity.setContent(JsonUtils.toJsonString(properties));
assignmentTaskDAO.updateById(assignmentTaskEntity);
}
ScheduleModeEnum systemScheduled = ScheduleModeEnum.SYSTEM_SCHEDULED;
if (assignmentTaskEntity.getScheduleMode() == systemScheduled) {
scheduleService.scheduleTask(assignmentTaskEntity.getId(), systemScheduled);
}
}
@Transactional(rollbackFor = Exception.class)
public void runAssignments(List<Long> ids) {
checkAssignmentAllExist(ids);
List<AssignmentTaskEntity> tasks = new ArrayList<>();
for (Long id : ids) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (assignmentTaskEntity.getPublished()) {
tasks.add(assignmentTaskEntity);
} else {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_NOT_DEPLOY, "ID=" + id);
}
}
}
tasks.forEach(assignmentTask -> {
scheduleService.scheduleTask(assignmentTask.getId(), ScheduleModeEnum.MANUAL);
});
@Transactional(rollbackFor = Exception.class)
public void runAssignments(List<Long> ids) {
checkAssignmentAllExist(ids);
List<AssignmentTaskEntity> tasks = new ArrayList<>();
for (Long id : ids) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (assignmentTaskEntity.getPublished()) {
tasks.add(assignmentTaskEntity);
} else {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_NOT_DEPLOY, "ID=" + id);
}
}
}
tasks.forEach(assignmentTask -> {
scheduleService.scheduleTask(assignmentTask.getId(), ScheduleModeEnum.MANUAL);
});
@Transactional(rollbackFor = Exception.class)
public void retireAssignments(List<Long> ids) {
checkAssignmentAllExist(ids);
for (Long id : ids) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (Objects.nonNull(assignmentTaskEntity.getPublished())
&& assignmentTaskEntity.getPublished()) {
String jobKey = assignmentTaskEntity.getJobKey();
scheduleService.cancelByJobKey(jobKey);
scheduleService.cancelManualJob(id);
assignmentTaskEntity.setPublished(Boolean.FALSE);
assignmentTaskEntity.setContent("{}");
assignmentTaskEntity.setJobKey("");
assignmentTaskDAO.updateById(assignmentTaskEntity);
}
}
}
}
private void checkAssignmentAllExist(List<Long> ids) {
for (Long id : ids) {
if (Objects.isNull(assignmentTaskDAO.getById(id))) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_NOT_EXISTS, "ID=" + id);
}
}
}
@Transactional(rollbackFor = Exception.class)
public void retireAssignments(List<Long> ids) {
checkAssignmentAllExist(ids);
for (Long id : ids) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
if (Objects.nonNull(assignmentTaskEntity.getPublished())
&& assignmentTaskEntity.getPublished()) {
String jobKey = assignmentTaskEntity.getJobKey();
scheduleService.cancelByJobKey(jobKey);
scheduleService.cancelManualJob(id);
assignmentTaskEntity.setPublished(Boolean.FALSE);
assignmentTaskEntity.setContent("{}");
assignmentTaskEntity.setJobKey("");
assignmentTaskDAO.updateById(assignmentTaskEntity);
}
}
}
private SourceDataSourceProperties getSourceDataSourceProperties(
AssignmentConfigEntity assignmentConfigEntity) {
SourceDataSourceProperties sourceDataSourceProperties = new SourceDataSourceProperties();
DatabaseConnectionEntity sourceDatabaseConnectionEntity = databaseConnectionDAO.getById(
assignmentConfigEntity.getSourceConnectionId()
);
File driverVersionFile = driverLoadService.getVersionDriverFile(
sourceDatabaseConnectionEntity.getType(),
sourceDatabaseConnectionEntity.getVersion());
sourceDataSourceProperties.setUrl(sourceDatabaseConnectionEntity.getUrl());
sourceDataSourceProperties.setDriverClassName(sourceDatabaseConnectionEntity.getDriver());
sourceDataSourceProperties.setDriverPath(driverVersionFile.getAbsolutePath());
sourceDataSourceProperties.setUsername(sourceDatabaseConnectionEntity.getUsername());
sourceDataSourceProperties.setPassword(sourceDatabaseConnectionEntity.getPassword());
private void checkAssignmentAllExist(List<Long> ids) {
for (Long id : ids) {
if (Objects.isNull(assignmentTaskDAO.getById(id))) {
throw new DbswitchException(ResultCode.ERROR_RESOURCE_NOT_EXISTS, "ID=" + id);
}
}
}
String sourceSchema = assignmentConfigEntity.getSourceSchema();
if (assignmentConfigEntity.getExcluded()) {
if (CollectionUtils.isEmpty(assignmentConfigEntity.getSourceTables())) {
sourceDataSourceProperties.setSourceExcludes("");
} else {
sourceDataSourceProperties.setSourceExcludes(
assignmentConfigEntity.getSourceTables()
.stream().collect(Collectors.joining(","))
);
}
} else {
if (CollectionUtils.isEmpty(assignmentConfigEntity.getSourceTables())) {
sourceDataSourceProperties.setSourceIncludes("");
} else {
sourceDataSourceProperties.setSourceIncludes(
assignmentConfigEntity.getSourceTables()
.stream().collect(Collectors.joining(","))
);
}
}
sourceDataSourceProperties.setSourceSchema(sourceSchema);
sourceDataSourceProperties.setRegexTableMapper(assignmentConfigEntity.getTableNameMap());
sourceDataSourceProperties.setRegexColumnMapper(assignmentConfigEntity.getColumnNameMap());
sourceDataSourceProperties.setFetchSize(assignmentConfigEntity.getBatchSize());
sourceDataSourceProperties.setTableType(assignmentConfigEntity.getTableType().name());
return sourceDataSourceProperties;
}
private SourceDataSourceProperties getSourceDataSourceProperties(
AssignmentConfigEntity assignmentConfigEntity) {
SourceDataSourceProperties sourceDataSourceProperties = new SourceDataSourceProperties();
DatabaseConnectionEntity sourceDatabaseConnectionEntity = databaseConnectionDAO.getById(
assignmentConfigEntity.getSourceConnectionId()
);
File driverVersionFile = driverLoadService.getVersionDriverFile(
sourceDatabaseConnectionEntity.getType(),
sourceDatabaseConnectionEntity.getVersion());
sourceDataSourceProperties.setUrl(sourceDatabaseConnectionEntity.getUrl());
sourceDataSourceProperties.setDriverClassName(sourceDatabaseConnectionEntity.getDriver());
sourceDataSourceProperties.setDriverPath(driverVersionFile.getAbsolutePath());
sourceDataSourceProperties.setUsername(sourceDatabaseConnectionEntity.getUsername());
sourceDataSourceProperties.setPassword(sourceDatabaseConnectionEntity.getPassword());
private TargetDataSourceProperties getTargetDataSourceProperties(
AssignmentConfigEntity assignmentConfigEntity) {
TargetDataSourceProperties targetDataSourceProperties = new TargetDataSourceProperties();
DatabaseConnectionEntity targetDatabaseConnectionEntity = databaseConnectionDAO
.getById(assignmentConfigEntity.getTargetConnectionId());
File driverVersionFile = driverLoadService.getVersionDriverFile(
targetDatabaseConnectionEntity.getType(),
targetDatabaseConnectionEntity.getVersion());
targetDataSourceProperties.setUrl(targetDatabaseConnectionEntity.getUrl());
targetDataSourceProperties.setDriverClassName(targetDatabaseConnectionEntity.getDriver());
targetDataSourceProperties.setDriverPath(driverVersionFile.getAbsolutePath());
targetDataSourceProperties.setUsername(targetDatabaseConnectionEntity.getUsername());
targetDataSourceProperties.setPassword(targetDatabaseConnectionEntity.getPassword());
targetDataSourceProperties.setTargetSchema(assignmentConfigEntity.getTargetSchema());
if (assignmentConfigEntity.getTargetDropTable()) {
targetDataSourceProperties.setTargetDrop(Boolean.TRUE);
targetDataSourceProperties.setChangeDataSync(Boolean.FALSE);
} else {
targetDataSourceProperties.setTargetDrop(Boolean.FALSE);
targetDataSourceProperties.setChangeDataSync(Boolean.TRUE);
}
if (assignmentConfigEntity.getTargetOnlyCreate()) {
targetDataSourceProperties.setOnlyCreate(Boolean.TRUE);
}
if (assignmentConfigEntity.getTargetAutoIncrement()) {
targetDataSourceProperties.setCreateTableAutoIncrement(Boolean.TRUE);
}
targetDataSourceProperties.setTableNameCase(assignmentConfigEntity.getTableNameCase());
targetDataSourceProperties.setColumnNameCase(assignmentConfigEntity.getColumnNameCase());
targetDataSourceProperties.setTargetSyncOption(assignmentConfigEntity.getTargetSyncOption());
targetDataSourceProperties.setBeforeSqlScripts(assignmentConfigEntity.getBeforeSqlScripts());
targetDataSourceProperties.setAfterSqlScripts(assignmentConfigEntity.getAfterSqlScripts());
String sourceSchema = assignmentConfigEntity.getSourceSchema();
if (assignmentConfigEntity.getExcluded()) {
if (CollectionUtils.isEmpty(assignmentConfigEntity.getSourceTables())) {
sourceDataSourceProperties.setSourceExcludes("");
} else {
sourceDataSourceProperties.setSourceExcludes(
assignmentConfigEntity.getSourceTables()
.stream().collect(Collectors.joining(","))
);
}
} else {
if (CollectionUtils.isEmpty(assignmentConfigEntity.getSourceTables())) {
sourceDataSourceProperties.setSourceIncludes("");
} else {
sourceDataSourceProperties.setSourceIncludes(
assignmentConfigEntity.getSourceTables()
.stream().collect(Collectors.joining(","))
);
}
}
sourceDataSourceProperties.setSourceSchema(sourceSchema);
sourceDataSourceProperties.setRegexTableMapper(assignmentConfigEntity.getTableNameMap());
sourceDataSourceProperties.setRegexColumnMapper(assignmentConfigEntity.getColumnNameMap());
sourceDataSourceProperties.setFetchSize(assignmentConfigEntity.getBatchSize());
sourceDataSourceProperties.setTableType(assignmentConfigEntity.getTableType().name());
return sourceDataSourceProperties;
}
return targetDataSourceProperties;
}
private TargetDataSourceProperties getTargetDataSourceProperties(
AssignmentConfigEntity assignmentConfigEntity) {
TargetDataSourceProperties targetDataSourceProperties = new TargetDataSourceProperties();
DatabaseConnectionEntity targetDatabaseConnectionEntity = databaseConnectionDAO
.getById(assignmentConfigEntity.getTargetConnectionId());
File driverVersionFile = driverLoadService.getVersionDriverFile(
targetDatabaseConnectionEntity.getType(),
targetDatabaseConnectionEntity.getVersion());
targetDataSourceProperties.setUrl(targetDatabaseConnectionEntity.getUrl());
targetDataSourceProperties.setDriverClassName(targetDatabaseConnectionEntity.getDriver());
targetDataSourceProperties.setDriverPath(driverVersionFile.getAbsolutePath());
targetDataSourceProperties.setUsername(targetDatabaseConnectionEntity.getUsername());
targetDataSourceProperties.setPassword(targetDatabaseConnectionEntity.getPassword());
targetDataSourceProperties.setTargetSchema(assignmentConfigEntity.getTargetSchema());
if (assignmentConfigEntity.getTargetDropTable()) {
targetDataSourceProperties.setTargetDrop(Boolean.TRUE);
targetDataSourceProperties.setChangeDataSync(Boolean.FALSE);
} else {
targetDataSourceProperties.setTargetDrop(Boolean.FALSE);
targetDataSourceProperties.setChangeDataSync(Boolean.TRUE);
}
if (assignmentConfigEntity.getTargetOnlyCreate()) {
targetDataSourceProperties.setOnlyCreate(Boolean.TRUE);
}
if (assignmentConfigEntity.getTargetAutoIncrement()) {
targetDataSourceProperties.setCreateTableAutoIncrement(Boolean.TRUE);
}
targetDataSourceProperties.setTableNameCase(assignmentConfigEntity.getTableNameCase());
targetDataSourceProperties.setColumnNameCase(assignmentConfigEntity.getColumnNameCase());
targetDataSourceProperties.setTargetSyncOption(assignmentConfigEntity.getTargetSyncOption());
targetDataSourceProperties.setBeforeSqlScripts(assignmentConfigEntity.getBeforeSqlScripts());
targetDataSourceProperties.setAfterSqlScripts(assignmentConfigEntity.getAfterSqlScripts());
private GlobalParamConfigProperties getGlobalParamConfigProperties(
AssignmentConfigEntity assignmentConfigEntity) {
GlobalParamConfigProperties configProperties = new GlobalParamConfigProperties();
configProperties.setChannelQueueSize(assignmentConfigEntity.getChannelSize());
return configProperties;
}
return targetDataSourceProperties;
}
private GlobalParamConfigProperties getGlobalParamConfigProperties(
AssignmentConfigEntity assignmentConfigEntity) {
GlobalParamConfigProperties configProperties = new GlobalParamConfigProperties();
configProperties.setChannelQueueSize(assignmentConfigEntity.getChannelSize());
return configProperties;
}
public void exportAssignments(List<Long> ids, HttpServletResponse response) {
checkAssignmentAllExist(ids);
List<AssignmentsDataResponse> assignmentsDataResponses = new ArrayList<>();
// TODO 任务导出
for (Long id : ids) {
AssignmentTaskEntity assignmentTaskEntity = assignmentTaskDAO.getById(id);
// AssignmentsDataResponse assignmentsDataResponse =
// this.assignmentConvert.toAssignmentsDataResponse(assignmentTaskEntity);
AssignmentsDataResponse assignmentsDataResponse = ConverterFactory.getConverter(AssignmentsConverter.class)
.convert(assignmentTaskEntity);
AssignmentConfigEntity assignmentConfigEntity = this.assignmentConfigDAO.getByAssignmentTaskId(id);
Long sourceConnectionId = assignmentConfigEntity.getSourceConnectionId();
DatabaseConnectionEntity databaseConnectionEntity = this.databaseConnectionDAO.getById(sourceConnectionId);
String sourceSchema = assignmentConfigEntity.getSourceSchema();
assignmentsDataResponse.setSourceSchema(sourceSchema);
String sourceType = databaseConnectionEntity.getType().getName();
assignmentsDataResponse.setSourceType(sourceType);
Long targetConnectionId = assignmentConfigEntity.getTargetConnectionId();
DatabaseConnectionEntity databaseConnectionEntity1 = this.databaseConnectionDAO.getById(targetConnectionId);
String targetSchema = assignmentConfigEntity.getTargetSchema();
assignmentsDataResponse.setTargetSchema(targetSchema);
String targetType = databaseConnectionEntity1.getType().getName();
assignmentsDataResponse.setTargetType(targetType);
AssignmentJobEntity assignmentJobEntity = this.assignmentJobMapper.selectOne(
new LambdaQueryWrapper<AssignmentJobEntity>()
.eq(AssignmentJobEntity::getAssignmentId, assignmentsDataResponse.getId()).orderByDesc(AssignmentJobEntity::getCreateTime)
.last(" limit 1 "));
Integer status = (assignmentJobEntity == null || assignmentJobEntity.getStatus() == null) ?
JobStatusEnum.INIT.getValue() :
assignmentJobEntity.getStatus();
assignmentsDataResponse.setRunStatus(JobStatusEnum.of(status).getName());
assignmentsDataResponses.add(assignmentsDataResponse);
}
try {
// 这里注意 有同学反应使用swagger 会导致各种问题请直接用浏览器或者用postman
// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
// response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), AssignmentsDataResponse.class)
.sheet("模板")
.doWrite(assignmentsDataResponses);
} catch (IOException ex) {
throw new DbswitchException(ResultCode.ERROR_INTERNAL_ERROR, ex.getMessage());
}
}
}

View File

@@ -16,7 +16,7 @@ import lombok.Getter;
@AllArgsConstructor
public enum JobStatusEnum {
INIT(0, "执行"),
INIT(0, "执行"),
RUNNING(1, "执行中"),
FAIL(2, "执行异常"),
PASS(3, "执行成功"),

12
pom.xml
View File

@@ -128,6 +128,18 @@
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
</dependencies>
</dependencyManagement>