沙钢智慧能源系统后端代码
dengzedong
2024-11-29 94c44ef9835e1a3713184cfe31c4917d0f0e688e
定时任务 + feign请求拦截添加token和租户id
已修改18个文件
已删除16个文件
已添加4个文件
1101 ■■■■■ 文件已修改
shasteel-biz/pom.xml 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/config/FeignTokenInterceptor.java 41 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/DemoController.java 90 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/vo/DemoPageReqVO.java 23 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/vo/DemoRespVO.java 59 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/vo/DemoSaveReqVO.java 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/package-info.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/app/ip/AppAreaController.java 34 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/app/ip/vo/AppAreaNodeRespVO.java 23 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/app/package-info.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/package-info.java 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/dataobject/demo/DemoDO.java 62 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/dataobject/package-info.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/mysql/demo/DemoMapper.java 24 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/mysql/package-info.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/framework/rpc/config/RpcConfiguration.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/controller/admin/ScheduleJobController.java 82 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/controller/admin/ScheduleJobLogController.java 37 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dao/ScheduleJobDao.java 17 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dao/ScheduleJobLogDao.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dto/ScheduleJobDTO.java 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dto/ScheduleJobLogDTO.java 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/entity/ScheduleJobEntity.java 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/entity/ScheduleJobLogEntity.java 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/init/JobCommandLineRunner.java 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/ScheduleJobLogService.java 10 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/ScheduleJobService.java 13 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/impl/ScheduleJobLogServiceImpl.java 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/impl/ScheduleJobServiceImpl.java 53 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/ITask.java 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunPredictModuleTask.java 45 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/utils/ScheduleJob.java 14 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/utils/ScheduleUtils.java 15 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/service/demo/DemoService.java 24 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/service/demo/DemoServiceImpl.java 56 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/service/package-info.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/util/SpringContextUtils.java 47 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/src/main/java/com/iailab/module/shasteel/util/token/IailabClient.java 158 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shasteel-biz/pom.xml
@@ -29,6 +29,11 @@
            <artifactId>iailab-module-infra-api</artifactId>
            <version>${revision}</version>
        </dependency>
        <dependency>
            <groupId>com.iailab</groupId>
            <artifactId>iailab-module-model-api</artifactId>
            <version>${revision}</version>
        </dependency>
        <!-- 业务组件 -->
        <dependency>
@@ -131,6 +136,23 @@
            <artifactId>tencentcloud-sdk-java-sms</artifactId> <!-- 短信(腾讯云) -->
        </dependency>
        <!-- 定时任务 -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.2</version>
            <exclusions>
                <exclusion>
                    <groupId>com.mchange</groupId>
                    <artifactId>c3p0</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.zaxxer</groupId>
                    <artifactId>HikariCP-java6</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
shasteel-biz/src/main/java/com/iailab/module/shasteel/config/FeignTokenInterceptor.java
对比新文件
@@ -0,0 +1,41 @@
package com.iailab.module.shasteel.config;
import com.iailab.module.shasteel.util.token.IailabClient;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Configuration
public class FeignTokenInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 从当前请求上下文中获取Token
        String token = getTokenFromCurrentRequest();
        if (token == null) {
            // 如果没有获取到Token,从system-server中获取token
            token = IailabClient.getToken();
        }
        if (token!= null) {
            requestTemplate.header(HttpHeaders.AUTHORIZATION, token);
        }
        Long tenantId = IailabClient.getTenantId();
        if (tenantId != null) {
            requestTemplate.header("tenant-id", String.valueOf(tenantId));
        }
    }
    private String getTokenFromCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes!= null) {
            return attributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
        }
        return null;
    }
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/DemoController.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/vo/DemoPageReqVO.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/vo/DemoRespVO.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/demo/vo/DemoSaveReqVO.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/admin/package-info.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/app/ip/AppAreaController.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/app/ip/vo/AppAreaNodeRespVO.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/app/package-info.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/controller/package-info.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/dataobject/demo/DemoDO.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/dataobject/package-info.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/mysql/demo/DemoMapper.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/dal/mysql/package-info.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/framework/rpc/config/RpcConfiguration.java
@@ -4,11 +4,12 @@
import com.iailab.module.infra.api.db.DataSourceConfigServiceApi;
import com.iailab.module.infra.api.file.FileApi;
import com.iailab.module.infra.api.websocket.WebSocketSenderApi;
import com.iailab.module.model.api.mdk.MdkApi;
import com.iailab.module.system.api.tenant.TenantApi;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = {FileApi.class, WebSocketSenderApi.class, DataSourceConfigServiceApi.class, ConfigApi.class, TenantApi.class})
@EnableFeignClients(clients = {FileApi.class, WebSocketSenderApi.class, DataSourceConfigServiceApi.class, ConfigApi.class, TenantApi.class, MdkApi.class})
public class RpcConfiguration {
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/controller/admin/ScheduleJobController.java
@@ -1,24 +1,14 @@
package com.iailab.module.shasteel.job.controller.admin;
import com.iailab.framework.common.page.PageData;
import com.iailab.framework.common.pojo.CommonResult;
import com.iailab.framework.common.pojo.PageResult;
import com.iailab.framework.common.util.object.BeanUtils;
import com.iailab.framework.common.util.validation.ValidationUtils;
import com.iailab.framework.common.validation.group.AddGroup;
import com.iailab.framework.common.validation.group.DefaultGroup;
import com.iailab.framework.common.validation.group.UpdateGroup;
import com.iailab.framework.tenant.core.context.TenantContextHolder;
import com.iailab.module.shasteel.job.dto.ScheduleJobDTO;
import com.iailab.module.shasteel.job.entity.ScheduleJobEntity;
import com.iailab.module.shasteel.job.service.ScheduleJobService;
import com.iailab.module.shasteel.job.vo.ScheduleJobReqVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
import static com.iailab.framework.common.pojo.CommonResult.success;
@@ -29,89 +19,73 @@
 */
@RestController
@RequestMapping("/shasteel/job/schedule")
@Tag(name = "定时任务")
public class ScheduleJobController {
    @Resource
    @Autowired
    private ScheduleJobService scheduleJobService;
    @GetMapping("page")
    @Operation(summary = "分页")
    @PreAuthorize("@ss.hasPermission('shasteel:schedule:query')")
    public CommonResult<PageResult<ScheduleJobDTO>> page(@Validated ScheduleJobReqVO reqVO){
        reqVO.setTenantId(TenantContextHolder.getTenantId());
        PageResult<ScheduleJobEntity> page = scheduleJobService.page(reqVO);
    @PreAuthorize("@ss.hasPermission('shasteel:job:query')")
    public CommonResult<PageData<ScheduleJobDTO>> page(@RequestParam Map<String, Object> params){
        PageData<ScheduleJobDTO> page = scheduleJobService.page(params);
        return success(BeanUtils.toBean(page, ScheduleJobDTO.class));
        return success(page);
    }
    @GetMapping("info")
    @Operation(summary = "信息")
    @PreAuthorize("@ss.hasPermission('shasteel:schedule:query')")
    public CommonResult<ScheduleJobDTO> info(@RequestParam("id") Long id){
    @GetMapping("{id}")
    @PreAuthorize("@ss.hasPermission('shasteel:job:query')")
    public CommonResult<ScheduleJobDTO> info(@PathVariable("id") Long id){
        ScheduleJobDTO schedule = scheduleJobService.get(id);
        
        return new CommonResult<ScheduleJobDTO>().setData(schedule);
        return success(schedule);
    }
    @PostMapping("/create")
    @Operation(summary = "保存")
    @PreAuthorize("@ss.hasPermission('shasteel:schedule:create')")
    @PostMapping
    @PreAuthorize("@ss.hasPermission('shasteel:job:create')")
    public CommonResult save(@RequestBody ScheduleJobDTO dto){
        ValidationUtils.validate(dto, AddGroup.class, DefaultGroup.class);
        scheduleJobService.save(dto);
        
        return new CommonResult();
        return success();
    }
    @PutMapping("/update")
    @Operation(summary = "修改")
    @PreAuthorize("@ss.hasPermission('shasteel:schedule:update')")
    @PutMapping
    @PreAuthorize("@ss.hasPermission('shasteel:job:update')")
    public CommonResult update(@RequestBody ScheduleJobDTO dto){
        ValidationUtils.validate(dto, UpdateGroup.class, DefaultGroup.class);
        scheduleJobService.update(dto);
        
        return new CommonResult();
        return success();
    }
    @DeleteMapping("/delete")
    @Operation(summary = "删除")
    @PreAuthorize("@ss.hasPermission('shasteel:schedule:delete')")
    public CommonResult delete(@RequestParam("id") Long id){
        scheduleJobService.deleteBatch(id);
        return new CommonResult();
    @DeleteMapping
    @PreAuthorize("@ss.hasPermission('shasteel:job:delete')")
    public CommonResult delete(@RequestParam Long id){
        scheduleJobService.deleteById(id);
        return success();
    }
    @PutMapping("/run")
    @Operation(summary = "立即执行")
    public CommonResult run(@RequestParam("id") Long id){
        Long[] ids = new Long[1];
        ids[0] = id;
        scheduleJobService.run(ids);
        scheduleJobService.run(id);
        
        return new CommonResult();
        return success();
    }
    @PutMapping("/pause")
    @Operation(summary = "暂停")
    public CommonResult pause(@RequestParam("id") Long id){
        Long[] ids = new Long[1];
        ids[0] = id;
        scheduleJobService.pause(ids);
        
        return new CommonResult();
        return success();
    }
    @PutMapping("/resume")
    @Operation(summary = "恢复")
    public CommonResult resume(@RequestParam("id") Long id){
        Long[] ids = new Long[1];
        ids[0] = id;
        scheduleJobService.resume(ids);
        
        return new CommonResult();
        return success();
    }
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/controller/admin/ScheduleJobLogController.java
@@ -1,27 +1,16 @@
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
package com.iailab.module.shasteel.job.controller.admin;
import com.iailab.framework.common.constant.Constant;
import com.iailab.framework.common.page.PageData;
import com.iailab.framework.common.pojo.CommonResult;
import com.iailab.module.shasteel.job.dto.ScheduleJobLogDTO;
import com.iailab.module.shasteel.job.service.ScheduleJobLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
import static com.iailab.framework.common.pojo.CommonResult.success;
/**
 * 定时任务日志
@@ -29,34 +18,22 @@
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/scheduleLog")
@Tag(name = "定时任务日志")
@RequestMapping("/mcs/scheduleLog")
public class ScheduleJobLogController {
    @Resource
    @Autowired
    private ScheduleJobLogService scheduleJobLogService;
    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
        @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true) ,
        @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true) ,
        @Parameter(name = Constant.ORDER_FIELD, description = "排序字段") ,
        @Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)") ,
        @Parameter(name = "jobId", description = "jobId")
    })
    @PreAuthorize("@ss.hasPermission('sys:schedule:log')")
    public CommonResult<PageData<ScheduleJobLogDTO>> page(@RequestParam Map<String, Object> params){
        PageData<ScheduleJobLogDTO> page = scheduleJobLogService.page(params);
        
        return new CommonResult<PageData<ScheduleJobLogDTO>>().setData(page);
        return success(page);
    }
    @GetMapping("{id}")
    @Operation(summary = "信息")
    @PreAuthorize("@ss.hasPermission('sys:schedule:log')")
    public CommonResult<ScheduleJobLogDTO> info(@PathVariable("id") Long id){
        ScheduleJobLogDTO log = scheduleJobLogService.get(id);
        
        return new CommonResult<ScheduleJobLogDTO>().setData(log);
        return success(log);
    }
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dao/ScheduleJobDao.java
@@ -1,11 +1,7 @@
package com.iailab.module.shasteel.job.dao;
import com.baomidou.dynamic.datasource.annotation.Master;
import com.iailab.framework.common.pojo.PageResult;
import com.iailab.framework.mybatis.core.mapper.BaseMapperX;
import com.iailab.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.iailab.framework.common.dao.BaseDao;
import com.iailab.module.shasteel.job.entity.ScheduleJobEntity;
import com.iailab.module.shasteel.job.vo.ScheduleJobReqVO;
import org.apache.ibatis.annotations.Mapper;
import java.util.Map;
@@ -15,17 +11,8 @@
 *
 * @author Mark sunlightcs@gmail.com
 */
@Master
@Mapper
public interface ScheduleJobDao extends BaseMapperX<ScheduleJobEntity> {
    default PageResult<ScheduleJobEntity> selectPage(ScheduleJobReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<ScheduleJobEntity>()
                .likeIfPresent(ScheduleJobEntity::getBeanName, reqVO.getBeanName())
                .eqIfPresent(ScheduleJobEntity::getTenantId, reqVO.getTenantId())
                .orderByDesc(ScheduleJobEntity::getCreateDate));
    }
public interface ScheduleJobDao extends BaseDao<ScheduleJobEntity> {
    
    /**
     * 批量更新状态
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dao/ScheduleJobLogDao.java
@@ -1,6 +1,5 @@
package com.iailab.module.shasteel.job.dao;
import com.baomidou.dynamic.datasource.annotation.Master;
import com.iailab.framework.common.dao.BaseDao;
import com.iailab.module.shasteel.job.entity.ScheduleJobLogEntity;
import org.apache.ibatis.annotations.Mapper;
@@ -10,7 +9,6 @@
 *
 * @author Mark sunlightcs@gmail.com
 */
@Master
@Mapper
public interface ScheduleJobLogDao extends BaseDao<ScheduleJobLogEntity> {
    
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dto/ScheduleJobDTO.java
@@ -1,24 +1,7 @@
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
package com.iailab.module.shasteel.job.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.iailab.framework.common.validation.group.AddGroup;
import com.iailab.framework.common.validation.group.DefaultGroup;
import com.iailab.framework.common.validation.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import java.io.Serializable;
import java.util.Date;
@@ -29,34 +12,21 @@
 * @since 1.0.0
 */
@Data
@Tag(name = "定时任务")
public class ScheduleJobDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    @Schema(description = "id")
    @Null(message="{id.null}", groups = AddGroup.class)
    @NotNull(message="{id.require}", groups = UpdateGroup.class)
    private Long id;
    @Schema(description = "spring bean名称")
    @NotBlank(message = "{schedule.bean.require}", groups = DefaultGroup.class)
    private String beanName;
    @Schema(description = "参数")
    private String params;
    @Schema(description = "cron表达式")
    @NotBlank(message = "{schedule.cron.require}", groups = DefaultGroup.class)
    private String cronExpression;
    @Schema(description = "任务状态  0:暂停  1:正常")
    private Integer status;
    @Schema(description = "备注")
    private String remark;
    @Schema(description = "创建时间")
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private Date createDate;
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/dto/ScheduleJobLogDTO.java
@@ -1,15 +1,5 @@
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
package com.iailab.module.shasteel.job.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import java.io.Serializable;
@@ -22,32 +12,23 @@
 * @since 1.0.0
 */
@Data
@Tag(name = "定时任务日志")
public class ScheduleJobLogDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    @Schema(description = "id")
    private Long id;
    @Schema(description = "任务id")
    private Long jobId;
    @Schema(description = "spring bean名称")
    private String beanName;
    @Schema(description = "参数")
    private String params;
    @Schema(description = "任务状态    0:失败    1:成功")
    private Integer status;
    @Schema(description = "失败信息")
    private String error;
    @Schema(description = "耗时(单位:毫秒)")
    private Integer times;
    @Schema(description = "创建时间")
    private Date createDate;
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/entity/ScheduleJobEntity.java
@@ -50,9 +50,4 @@
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateDate;
    /**
     * 多租户编号
     */
    private Long tenantId;
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/entity/ScheduleJobLogEntity.java
@@ -51,9 +51,4 @@
     */
    private Date createDate;
    /**
     * 多租户编号
     */
    private Long tenantId;
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/init/JobCommandLineRunner.java
@@ -6,20 +6,22 @@
import com.iailab.module.shasteel.job.utils.ScheduleUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
 * 初始化定时任务数据
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class JobCommandLineRunner implements CommandLineRunner {
    @Resource
    @Autowired
    private Scheduler scheduler;
    @Resource
    @Autowired
    private ScheduleJobDao scheduleJobDao;
    @Override
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/ScheduleJobLogService.java
@@ -1,18 +1,10 @@
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
package com.iailab.module.shasteel.job.service;
import com.iailab.framework.common.page.PageData;
import com.iailab.framework.common.service.BaseService;
import com.iailab.module.shasteel.job.dto.ScheduleJobLogDTO;
import com.iailab.module.shasteel.job.entity.ScheduleJobLogEntity;
import com.iailab.module.shasteel.job.dto.ScheduleJobLogDTO;
import java.util.Map;
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/ScheduleJobService.java
@@ -1,20 +1,21 @@
package com.iailab.module.shasteel.job.service;
import com.iailab.framework.common.pojo.PageResult;
import com.iailab.framework.common.page.PageData;
import com.iailab.framework.common.service.BaseService;
import com.iailab.module.shasteel.job.dto.ScheduleJobDTO;
import com.iailab.module.shasteel.job.entity.ScheduleJobEntity;
import com.iailab.module.shasteel.job.vo.ScheduleJobReqVO;
import java.util.Map;
/**
 * 定时任务
 *
 * @author Mark sunlightcs@gmail.com
 */
public interface ScheduleJobService{
public interface ScheduleJobService extends BaseService<ScheduleJobEntity> {
    PageResult<ScheduleJobEntity> page(ScheduleJobReqVO reqVO);
    PageData<ScheduleJobDTO> page(Map<String, Object> params);
    ScheduleJobDTO get(Long id);
@@ -31,7 +32,7 @@
    /**
     * 批量删除定时任务
     */
    void deleteBatch(Long id);
    void deleteBatch(Long[] ids);
    
    /**
     * 批量更新定时任务状态
@@ -41,7 +42,7 @@
    /**
     * 立即执行
     */
    void run(Long[] ids);
    void run(Long id);
    
    /**
     * 暂停运行
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/impl/ScheduleJobLogServiceImpl.java
@@ -1,16 +1,7 @@
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
package com.iailab.module.shasteel.job.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.iailab.framework.common.constant.Constant;
import com.iailab.framework.common.page.PageData;
import com.iailab.framework.common.service.impl.BaseServiceImpl;
import com.iailab.framework.common.util.object.ConvertUtils;
@@ -29,7 +20,7 @@
    @Override
    public PageData<ScheduleJobLogDTO> page(Map<String, Object> params) {
        IPage<ScheduleJobLogEntity> page = baseDao.selectPage(
            getPage(params, Constant.CREATE_DATE, false),
            getPage(params, "create_date", false),
            getWrapper(params)
        );
        return getPageData(page, ScheduleJobLogDTO.class);
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/service/impl/ScheduleJobServiceImpl.java
@@ -1,45 +1,45 @@
package com.iailab.module.shasteel.job.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.iailab.framework.common.constant.Constant;
import com.iailab.framework.common.pojo.PageResult;
import com.iailab.framework.common.page.PageData;
import com.iailab.framework.common.service.impl.BaseServiceImpl;
import com.iailab.framework.common.util.object.ConvertUtils;
import com.iailab.framework.security.core.util.SecurityFrameworkUtils;
import com.iailab.framework.tenant.core.context.TenantContextHolder;
import com.iailab.module.shasteel.job.dao.ScheduleJobDao;
import com.iailab.module.shasteel.job.dto.ScheduleJobDTO;
import com.iailab.module.shasteel.job.entity.ScheduleJobEntity;
import com.iailab.module.shasteel.job.service.ScheduleJobService;
import com.iailab.module.shasteel.job.utils.ScheduleUtils;
import com.iailab.module.shasteel.job.vo.ScheduleJobReqVO;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobDao, ScheduleJobEntity> implements ScheduleJobService {
    @Resource
public class ScheduleJobServiceImpl extends BaseServiceImpl<ScheduleJobDao, ScheduleJobEntity> implements ScheduleJobService {
    @Autowired
    private Scheduler scheduler;
    @Resource
    private ScheduleJobDao scheduleJobDao;
    @Override
    public PageResult<ScheduleJobEntity> page(ScheduleJobReqVO reqVO) {
        return scheduleJobDao.selectPage(reqVO);
    public PageData<ScheduleJobDTO> page(Map<String, Object> params) {
        IPage<ScheduleJobEntity> page = baseDao.selectPage(
            getPage(params, "create_date", false),
            getWrapper(params)
        );
        return getPageData(page, ScheduleJobDTO.class);
    }
    @Override
    public ScheduleJobDTO get(Long id) {
        ScheduleJobEntity entity = scheduleJobDao.selectById(id);
        ScheduleJobEntity entity = baseDao.selectById(id);
        return ConvertUtils.sourceToTarget(entity, ScheduleJobDTO.class);
    }
@@ -56,14 +56,12 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ScheduleJobDTO dto) {
        Long tenantId = TenantContextHolder.getRequiredTenantId();
        ScheduleJobEntity entity = ConvertUtils.sourceToTarget(dto, ScheduleJobEntity.class);
        entity.setId(System.currentTimeMillis());
        entity.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
        entity.setTenantId(tenantId);
        entity.setCreator(SecurityFrameworkUtils.getLoginUser().getId());
        entity.setCreateDate(new Date());
        scheduleJobDao.insert(entity);
        entity.setCreator(SecurityFrameworkUtils.getLoginUser().getId());
        entity.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
        this.insert(entity);
        
        ScheduleUtils.createScheduleJob(scheduler, entity);
    }
@@ -71,11 +69,9 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ScheduleJobDTO dto) {
        Long tenantId = TenantContextHolder.getRequiredTenantId();
        ScheduleJobEntity entity = ConvertUtils.sourceToTarget(dto, ScheduleJobEntity.class);
        entity.setUpdateDate(new Date());
        entity.setUpdater(SecurityFrameworkUtils.getLoginUser().getId());
        entity.setTenantId(tenantId);
        ScheduleUtils.updateScheduleJob(scheduler, entity);
                
        this.updateById(entity);
@@ -83,10 +79,13 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long id) {
        ScheduleUtils.deleteScheduleJob(scheduler, id);
    public void deleteBatch(Long[] ids) {
        for(Long id : ids){
            ScheduleUtils.deleteScheduleJob(scheduler, id);
        }
        scheduleJobDao.deleteById(id);
        //删除数据
        this.deleteBatchIds(Arrays.asList(ids));
    }
    @Override
@@ -94,15 +93,13 @@
        Map<String, Object> map = new HashMap<>(2);
        map.put("ids", ids);
        map.put("status", status);
        return scheduleJobDao.updateBatch(map);
        return baseDao.updateBatch(map);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(Long[] ids) {
        for(Long id : ids){
            ScheduleUtils.run(scheduler, scheduleJobDao.selectById(id));
        }
    public void run(Long id) {
        ScheduleUtils.run(scheduler, this.selectById(id));
    }
    @Override
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/ITask.java
@@ -1,11 +1,3 @@
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
package com.iailab.module.shasteel.job.task;
/**
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunPredictModuleTask.java
对比新文件
@@ -0,0 +1,45 @@
package com.iailab.module.shasteel.job.task;
import com.iailab.module.model.api.mdk.MdkApi;
import com.iailab.module.model.api.mdk.dto.MdkPredictReqDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Calendar;
/**
 * 执行模块预测定时任务
 *
 */
@Component("runPredictModuleTask")
public class RunPredictModuleTask implements ITask {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    MdkApi mdkApi;
    @Override
    public void run(String params) {
        logger.info("runPredictModuleTask定时任务正在执行,参数为:{}",params );
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND,0);
            MdkPredictReqDTO dto = new MdkPredictReqDTO();
            dto.setPredictTime(calendar.getTime());
            dto.setModuleType(params);
            mdkApi.predictModule(dto);
            logger.info(params + "模块预测完成");
        } catch (Exception ex) {
            logger.error("runPredictModuleTask运行异常");
            ex.printStackTrace();
        }
        logger.info("runPredictModuleTask运行完成");
    }
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/utils/ScheduleJob.java
@@ -2,11 +2,9 @@
import com.iailab.framework.common.constant.Constant;
import com.iailab.framework.common.exception.ExceptionUtils;
import com.iailab.framework.common.util.spring.SpringContextUtils;
import com.iailab.framework.tenant.core.context.TenantContextHolder;
import com.iailab.module.shasteel.job.entity.ScheduleJobEntity;
import com.iailab.module.shasteel.job.entity.ScheduleJobLogEntity;
import com.iailab.module.shasteel.job.service.ScheduleJobLogService;
import com.iailab.module.shasteel.util.SpringContextUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
@@ -31,18 +29,12 @@
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().
                get(ScheduleUtils.JOB_PARAM_KEY);
        //设置当前租户
        TenantContextHolder.setTenantId(scheduleJob.getTenantId());
        Long tenantId = TenantContextHolder.getRequiredTenantId();
        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setId(System.currentTimeMillis());
        log.setJobId(scheduleJob.getId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setParams(scheduleJob.getParams());
        log.setCreateDate(new Date());
        log.setTenantId(tenantId);
        //任务开始时间
        long startTime = System.currentTimeMillis();
@@ -73,8 +65,8 @@
            log.setError(ExceptionUtils.getErrorStackTrace(e));
        }finally {
            //获取spring bean
            ScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogService.class);
            scheduleJobLogService.insert(log);
            /*ScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogService.class);
            scheduleJobLogService.insert(log);*/
        }
    }
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/job/utils/ScheduleUtils.java
@@ -2,7 +2,6 @@
import com.iailab.framework.common.constant.Constant;
import com.iailab.framework.common.enums.ErrorCode;
import com.iailab.framework.common.exception.ServerException;
import com.iailab.module.shasteel.job.entity.ScheduleJobEntity;
import org.quartz.*;
@@ -39,7 +38,7 @@
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new ServerException(ErrorCode.JOB_ERROR, e.getMessage());
            throw new RuntimeException("获取表达式触发器异常", e);
        }
    }
@@ -68,7 +67,7 @@
                pauseJob(scheduler, scheduleJob.getId());
            }
        } catch (SchedulerException e) {
            throw new ServerException(ErrorCode.JOB_ERROR, e.getMessage());
            throw new RuntimeException("创建定时任务异常", e);
        }
    }
    
@@ -99,7 +98,7 @@
            }
            
        } catch (SchedulerException e) {
            throw new ServerException(ErrorCode.JOB_ERROR, e.getMessage());
            throw new RuntimeException("更新定时任务异常", e);
        }
    }
@@ -114,7 +113,7 @@
            
            scheduler.triggerJob(getJobKey(scheduleJob.getId()), dataMap);
        } catch (SchedulerException e) {
            throw new ServerException(ErrorCode.JOB_ERROR, e.getMessage());
            throw new RuntimeException("立即执行任务异常", e);
        }
    }
@@ -125,7 +124,7 @@
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new ServerException(ErrorCode.JOB_ERROR, e.getMessage());
            throw new RuntimeException("暂停任务异常", e);
        }
    }
@@ -136,7 +135,7 @@
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new ServerException(ErrorCode.JOB_ERROR, e.getMessage());
            throw new RuntimeException("恢复任务异常", e);
        }
    }
@@ -147,7 +146,7 @@
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new ServerException(ErrorCode.JOB_ERROR, e.getMessage());
            throw new RuntimeException("删除定时任务异常", e);
        }
    }
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/service/demo/DemoService.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/service/demo/DemoServiceImpl.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/service/package-info.java
文件已删除
shasteel-biz/src/main/java/com/iailab/module/shasteel/util/SpringContextUtils.java
对比新文件
@@ -0,0 +1,47 @@
package com.iailab.module.shasteel.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * Spring Context 工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    public static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }
    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }
    public static Class<? extends Object> getType(String name) {
        return applicationContext.getType(name);
    }
}
shasteel-biz/src/main/java/com/iailab/module/shasteel/util/token/IailabClient.java
对比新文件
@@ -0,0 +1,158 @@
package com.iailab.module.shasteel.util.token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
 * @author PanZhibao
 * @Description
 * @createTime 2024年11月21日
 */
@Slf4j
public class IailabClient {
    /**
     * 平台地址
     */
    public static String BASE_URL;
    /**
     * 租户编号
     */
    public static Long TENANT_ID;
    /**
     * 客户端信息
     */
    private static String CLIENT_ID;
    private static String CLIENT_SECRET;
    private static String USERNAME;
    private static String PASSWORD;
    private static final String GRAND_TYPE = "password";
    private static final String SCOPE = "user.read user.write";
    private static final RestTemplate restTemplate = new RestTemplate();
    // 鉴权token
    public static String accessToken;
    // 刷新token
    public static String refreshToken;
    // 鉴权token过期时间
    public static Long expireTime;
    private static final IailabClient iailabClient = new IailabClient();
    private IailabClient() {
//        BASE_URL = PlatApplicationContext.getProperty("iailab.baseUrl");
//        TENANT_ID = Long.parseLong(PlatApplicationContext.getProperty("iailab.tenantId"));
//        CLIENT_ID = PlatApplicationContext.getProperty("iailab.clientId");
//        CLIENT_SECRET = PlatApplicationContext.getProperty("iailab.clientSecret");
//        USERNAME = PlatApplicationContext.getProperty("iailab.username");
//        PASSWORD = PlatApplicationContext.getProperty("iailab.password");
        BASE_URL = "http://127.0.0.1:48080/admin-api/system";
        TENANT_ID = 172L;
        CLIENT_ID = "shasteel";
        CLIENT_SECRET = "shasteel111111111111111";
        USERNAME = "shasteel";
        PASSWORD = "123456";
    }
    public static IailabClient getInstance() {
        return iailabClient;
    }
    /**
     * 用户名密码方式获取平台token
     */
    private static synchronized void authenticate() {
        log.info("获取平台token");
        // 1.1 构建请求头
        HttpHeaders headers = new HttpHeaders();
        addClientHeader(headers);
        // 1.2 构建authenticate请求URL
        String authenticateUrl = BASE_URL + "/oauth2/token?"
                // 密码模式的参数
                + "grant_type=" + GRAND_TYPE
                + "&username=" + USERNAME
                + "&password=" + PASSWORD
                + "&scope=" + SCOPE;
        // 2. 执行请求
        ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
                authenticateUrl,
                HttpMethod.POST,
                new org.springframework.http.HttpEntity<>(headers),
                new ParameterizedTypeReference<Map<String, Object>>() {
                });
        Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");
        log.info(exchange.toString());
        Map<String, Object> authMap = exchange.getBody();
        accessToken = authMap.get("access_token").toString();
        refreshToken = authMap.get("refresh_token").toString();
        expireTime = Long.valueOf(authMap.get("expires_time").toString());
    }
    private static synchronized void refreshToken() {
        log.info("刷新token");
        // 1.1 构建请求头
        HttpHeaders headers = new HttpHeaders();
        addClientHeader(headers);
        // 1.2 构建authenticate请求URL
        String authenticateUrl = BASE_URL + "/system/auth/client-refresh-token?refreshToken=" + refreshToken
                + "&clientId=" + CLIENT_ID;
        // 2. 执行请求
        ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
                authenticateUrl,
                HttpMethod.POST,
                new org.springframework.http.HttpEntity<>(headers),
                new ParameterizedTypeReference<Map<String, Object>>() {
                });
        Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");
        Map<String, Object> authMap = exchange.getBody();
        //刷新token过期,重新获取token
        if (!ObjectUtils.isEmpty(authMap.get("code"))) {
            Integer code = Integer.valueOf(authMap.get("code").toString());
            if (code == 401) {
                authenticate();
            }
        } else {
            accessToken = authMap.get("access_token").toString();
            expireTime = Long.valueOf(authMap.get("expires_time").toString());
        }
    }
    private static void addClientHeader(HttpHeaders headers) {
        // client 拼接,需要 BASE64 编码
        String client = CLIENT_ID + ":" + CLIENT_SECRET;
        client = Base64Utils.encodeToString(client.getBytes(StandardCharsets.UTF_8));
        headers.add("Authorization", "Basic " + client);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("tenant-id", TENANT_ID.toString());
    }
    public static String getToken() {
        //第一次请求或者token过期,需要重新获取token
        if(ObjectUtils.isEmpty(IailabClient.accessToken)) {
            IailabClient.authenticate();
        } else if (IailabClient.expireTime < System.currentTimeMillis() / 1000) {
            IailabClient.refreshToken();
        }
        return accessToken;
    }
    public static Long getTenantId() {
        return TENANT_ID;
    }
}