svn to git

0 parents
Showing 47 changed files with 3036 additions and 0 deletions
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.glsx.framework</groupId>
<artifactId>framework-rpc-api</artifactId>
<version>2.0.0-SNAPSHOT</version>
</parent>
<groupId>cn.com.glsx.dj.dataprocessing</groupId>
<artifactId>rpc-dj-dataprocessing-api</artifactId>
<version>1.0-SNAPSHOT</version>
<name>rpc-dj-dataprocessing-api</name>
<properties>
<deploy.scanPackage>cn.com.glsx.dj.dataprocessing.remote</deploy.scanPackage>
</properties>
<build>
<plugins>
<plugin>
<groupId>cn.com.glsx.framework</groupId>
<artifactId>rpc-api-deploy-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>cn.com.glsx.dj.dataprocessing</groupId>
<artifactId>rpc-dj-dataprocessing-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package cn.com.glsx.dj.dataprocessing.dto;
import java.io.Serializable;
/**
* @Title: DemoDTO.java
* @Description:
* @author ${userName}
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@SuppressWarnings("serial")
public class DemoDTO implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package cn.com.glsx.dj.dataprocessing.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Description todo
* @Author yelq
* @Date 2025/5/28-10:34
* @Version 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReplaceDTO implements Serializable {
// 表名
private String tableName;
// 主键字段名
private String primaryKeyName;
// 主键值
private Integer primaryValue;
// 字段类型:0-简单文件链接,1-文本字符串含有多个文件链接
private Integer columnType;
// 字段名
private String columnName;
// 旧值
private String oldValue;
// 新值
private String updateValue;
}
package cn.com.glsx.dj.dataprocessing.enums;
\ No newline at end of file
package cn.com.glsx.dj.dataprocessing.model;
import java.io.Serializable;
/**
* @Title: DemoModel.java
* @Description:
* @author ${userName}
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@SuppressWarnings("serial")
public class DemoModel implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package cn.com.glsx.dj.dataprocessing.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
@Data
@Table(name = "public_data_backups")
public class PublicDataBackups implements Serializable {
/**
* 主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 表名
*/
@Column(name = "table_name")
private String tableName;
/**
* 字段名
*/
@Column(name = "column_name")
private String columnName;
/**
* 旧链接
*/
@Column(name = "old_url")
private String oldUrl;
/**
* 新链接
*/
@Column(name = "new_url")
private String newUrl;
/**
* 创建人
*/
@Column(name = "created_by")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "created_time")
private Date createdTime;
/**
* 修改人
*/
@Column(name = "updated_by")
private String updatedBy;
/**
* 修改时间
*/
@Column(name = "updated_time")
private Date updatedTime;
/**
* 删除标识(Y:已删除;N:未删除)
*/
@Column(name = "del_flag")
private String delFlag;
}
\ No newline at end of file
package cn.com.glsx.dj.dataprocessing.model;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
@ToString
@Data
@Table(name = "public_data_procesing")
public class PublicDataProcessing implements Serializable {
/**
* 主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 表名
*/
@Column(name = "table_name")
private String tableName;
/**
* 主键字段名
*/
@Column(name = "primary_key_name")
private String primaryKeyName;
/**
* 字段名
*/
@Column(name = "column_name")
private String columnName;
/**
* 字段类型:0-简单文件链接,1-文本字符串含有多个文件链接
*/
@Column(name = "column_type")
private Integer columnType;
/**
* 总条数
*/
@Column(name = "total_count")
private Integer totalCount;
/**
* 已完成条数
*/
@Column(name = "end_count")
private Integer endCount;
/**
* 是否已完成
*/
private Byte complete;
/**
* 创建人
*/
@Column(name = "created_by")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "created_time")
private Date createdTime;
/**
* 修改人
*/
@Column(name = "updated_by")
private String updatedBy;
/**
* 修改时间
*/
@Column(name = "updated_time")
private Date updatedTime;
/**
* 删除标识(Y:已删除;N:未删除)
*/
@Column(name = "del_flag")
private String delFlag;
/**
* 阿里云endpoint
*/
@Transient
private String endpoint;
/**
* 需要查询的关键字符串
*/
@Transient
private List<String> keywordList;
/**
* 要排除的id列表
*/
@Transient
private Integer limitId;
}
\ No newline at end of file
package cn.com.glsx.dj.dataprocessing.remote;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
import cn.com.glsx.dj.dataprocessing.dto.DemoDTO;
/**
* @Title: DemoService.java
* @Description:
* @author ${userName}
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
public interface DemoRemote {
DemoModel get(String name);
DemoDTO convert(DemoModel model);
}
# framework-archetype-rpc-api
RPC-API项目骨架
```properties
└─src
├─main
├─java
├─cn.com.glsx.dj.dataprocessing.dto 数据传输模型层
├─cn.com.glsx.dj.dataprocessing.enums 枚举定义
├─cn.com.glsx.dj.dataprocessing.model 数据模型层
└─cn.com.glsx.dj.dataprocessing.remote RPC暴露服务层
└─resources 资源文件目录
└─rpc
└─dubbo.xml dubbo接口配置
└─pom.xml pom文件
```
```properties
1、API改动后,请及时deploy到Maven仓库
```
```properties
1、rpc-api-deploy-maven-plugin api上报插件需配置当前api的jar包的引用。
```
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.glsx.framework</groupId>
<artifactId>framework-rpc</artifactId>
<version>2.0.0-SNAPSHOT</version>
</parent>
<groupId>cn.com.glsx.dj.dataprocessing</groupId>
<artifactId>rpc-dj-dataprocessing</artifactId>
<version>1.0-SNAPSHOT</version>
<name>rpc-dj-dataprocessing</name>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>cn.com.glsx.dj.dataprocessing</groupId>
<artifactId>rpc-dj-dataprocessing-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-elasticjob</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.18.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package cn.com.glsx.dj.dataprocessing;
import org.oreframework.boot.main.AbsOreBootStarter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* @Title: Main.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2015
*/
@SpringBootApplication
@ServletComponentScan
public class Main extends AbsOreBootStarter {
@Override
public void run(String[] args)
{
SpringApplication.run(Main.class, args);
}
public static void main(String[] args)
{
Main main = new Main();
main.run(args);
}
}
package cn.com.glsx.dj.dataprocessing.aliyun;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @Description 阿里云oss文件上传工具类
* @Author yelq
* @Date 2025/2/12-13:59
* @Version 1.0
*/
@Slf4j
@Service
public class AliyunOssFileUploadUtils {
@Autowired
private Environment env;
public String uploadFile(OssObjectUploadRequestDTO request) throws UnsupportedEncodingException {
Assert.notNull(request.getUploadData(), "上传文件不能为空!");
Assert.notNull(request.getFileType(), "上传文件类型不能为空!");
Assert.notNull(request.getFileName(), "上传文件名不能为空!");
String baseUrl = env.getProperty("aliyun.oss.base.url");
String endpoint = env.getProperty("aliyun.oss.endpoint");
// 预览模式(0-关闭,1-开启)
String previewEndpoint = env.getProperty("aliyun.oss.endpoint.preview");
Integer previewFlag = env.getProperty("aliyun.oss.endpoint.preview.flag", Integer.class, 0);
Assert.isTrue(previewFlag == 0 || previewFlag == 1, "预览模式配置错误!");
if (previewFlag == 1) {
Assert.isTrue(!StringUtils.isEmpty(previewEndpoint), "预览模式域名不能为空!");
}
// 内网访问地址
String intranetEndpoint = env.getProperty("aliyun.oss.endpoint.intranet");
Integer intranetFlag = env.getProperty("aliyun.oss.endpoint.intranet.flag", Integer.class, 0);
String accessKeyId = env.getProperty("aliyun.oss.accessKeyId");
String accessKeySecret = env.getProperty("aliyun.oss.accessKeySecret");
String bucketNameReportDefault = env.getProperty("aliyun.oss.bucketName.fastdfs.default");
Assert.notNull(baseUrl, "阿里云OSS配置不能为空!");
Assert.notNull(endpoint, "阿里云OSS配置不能为空!");
Assert.notNull(accessKeyId, "阿里云OSS配置不能为空!");
Assert.notNull(accessKeySecret, "阿里云OSS配置不能为空!");
Assert.notNull(bucketNameReportDefault, "阿里云OSS配置不能为空!");
String bucketName = StringUtils.isEmpty(request.getBucketName()) ? bucketNameReportDefault : request.getBucketName();
String respUrl = "";
log.info("endpointName:{}", intranetFlag == 1 ? intranetEndpoint : endpoint);
// 创建 OSSClient 实例,如果内网上传开关开启,则用内网上传
OSS ossClient = new OSSClientBuilder().build(intranetFlag == 1 ? intranetEndpoint : endpoint, accessKeyId, accessKeySecret);
try (
ByteArrayInputStream inputStream = new ByteArrayInputStream(request.getUploadData())
) {
// 2. 上传文件
log.info("文件 {} 开始上传...", request.getFileName());
ossClient.putObject(bucketName, request.getFileName(), inputStream);
log.info("文件 {}上传成功。", request.getFileName());
respUrl = baseUrl + bucketName + "." + endpoint + "/" + request.getFileName();
if (previewFlag == 1) {
// 预览模式开启
respUrl = baseUrl + previewEndpoint + "/" + request.getFileName();
}
log.info("文件链接:{}", respUrl);
} catch (OSSException oe) {
log.error("Error Message: {}", oe.getErrorMessage());
log.error("Error Code: {}", oe.getErrorCode());
log.error("Request ID: {}", oe.getRequestId());
log.error("Host ID: {}", oe.getHostId());
throw new RuntimeException("上传文件到阿里云OSS异常:" + oe.getMessage());
} catch (Exception ce) {
log.error("Error Message: {}", ce.getMessage());
throw new RuntimeException("上传文件到阿里云OSS异常:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return encodeUrlFileName(respUrl);
}
public static String encodeUrlFileName(String link) throws UnsupportedEncodingException {
String link1 = link.replace("http://", "").replace("https://", "");
String fileName = link1.substring(link1.lastIndexOf("/") + 1);
String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
return link.replace(fileName, encodeFileName);
}
}
package cn.com.glsx.dj.dataprocessing.aliyun;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
/**
* @Description 阿里云oss文件上传请求
* @Author yelq
* @Date 2025/2/12-15:32
* @Version 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class OssObjectUploadRequestDTO implements Serializable {
@ApiModelProperty(notes = "文件名称(带后缀)")
private String fileName;
@ApiModelProperty(notes = "文件内容")
private byte[] uploadData;
@ApiModelProperty(notes = "文件类型")
private String fileType;
@ApiModelProperty(notes = "文件在阿里云oss的分区")
private String bucketName;
}
package cn.com.glsx.dj.dataprocessing.config;
import org.oreframework.boot.autoconfigure.dubbo.reference.ReferenceBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @Title: DubboConfig.java
* @Description: Dubbo服务注册配置
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2018
*/
@Configuration
public class DubboConfig {
@Autowired
private ReferenceBuilderFactory factory;
/**
* 注册远程服务(示例)
* RpcRemote为需要调用的远程服务
* @return
*/
/*@Bean
public RpcRemote rpcApiMethodRemote(){
return factory.builder(RpcRemote.class).check(false).timeout(30000).build();
}*/
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package cn.com.glsx.dj.dataprocessing.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @Title: SystemProperty.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@Configuration
@ConfigurationProperties("system")
public class SystemProperty {
// 对应配置项:system.name
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package cn.com.glsx.dj.dataprocessing.converter;
import cn.com.glsx.framework.core.beans.converter.RpcBaseConverter;
import org.mapstruct.Mapper;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
import cn.com.glsx.dj.dataprocessing.dto.DemoDTO;
/**
* @Title: DemoConverter.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@Mapper(componentModel = "spring")
public abstract class DemoConverter extends RpcBaseConverter<DemoModel,DemoDTO>{
}
package cn.com.glsx.dj.dataprocessing.job;
import cn.com.glsx.dj.dataprocessing.service.PublicDataProcessingService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.Assert;
import java.util.Date;
/**
* @Description todo
* @Author yelq
* @Date 2025/6/3-17:21
* @Version 1.0
*/
@Slf4j
@ElasticJobConf(name = "AliyunOSSUrlReplaceFastdfsUrlJob", cron = "0 0 0 1 12 ? ", description = "阿里云OSS链接替换FastDfs的链接", overwrite = false)
public class AliyunOSSUrlReplaceFastdfsUrlJob implements SimpleJob {
@Autowired
private PublicDataProcessingService publicDataProcessingService;
@Autowired
private Environment env;
@Override
public void execute(ShardingContext shardingContext) {
try {
log.info("阿里云OSS链接替换FastDfs的链接开始");
// 执行时间段,超过这个时间段程序终止
String timeSlotStr = env.getProperty("aliyun.oss.url.replace.time.slot");
Assert.notNull(timeSlotStr, "执行时间不能为空!");
if (PublicDataProcessingService.checkTimeSlot(timeSlotStr)){
publicDataProcessingService.replaceFileUrl2AliyunOssUrl(timeSlotStr);
}
log.info("阿里云OSS链接替换FastDfs的链接结束");
} catch (Exception e) {
log.error("阿里云OSS链接替换FastDfs的链接失败:{}", e.getMessage(),e);
}
}
}
package cn.com.glsx.dj.dataprocessing.manager;
import org.springframework.stereotype.Service;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
/**
* @Title: DemoManager.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@Service
public class DemoManager{
public DemoModel load(){
return null;
}
}
package cn.com.glsx.dj.dataprocessing.mapper;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
/**
* @Title: DemoMapper.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@Mapper
public interface DemoMapper extends OreMapper<DemoModel> {
DemoModel load();
}
package cn.com.glsx.dj.dataprocessing.mapper;
import cn.com.glsx.dj.dataprocessing.model.PublicDataBackups;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
@Mapper
public interface PublicDataBackupsMapper extends OreMapper<PublicDataBackups> {
}
\ No newline at end of file
package cn.com.glsx.dj.dataprocessing.mapper;
import cn.com.glsx.dj.dataprocessing.dto.ReplaceDTO;
import cn.com.glsx.dj.dataprocessing.model.PublicDataProcessing;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
import java.util.Set;
@Mapper
public interface PublicDataProcessingMapper extends OreMapper<PublicDataProcessing> {
List<PublicDataProcessing> getTableConfig();
List<ReplaceDTO> getDataByOneConfig(PublicDataProcessing processing);
Integer getTotalCount(PublicDataProcessing processing);
Integer updateTableData(ReplaceDTO replaceDTO);
}
\ No newline at end of file
package cn.com.glsx.dj.dataprocessing.remote;
import org.springframework.beans.factory.annotation.Autowired;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
import cn.com.glsx.dj.dataprocessing.dto.DemoDTO;
import cn.com.glsx.dj.dataprocessing.service.DemoService;
import cn.com.glsx.dj.dataprocessing.converter.DemoConverter;
import org.apache.dubbo.config.annotation.DubboService;
/**
* @Title: DemoRemoteImpl.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@DubboService(retries = 0, timeout = 30000)
public class DemoRemoteImpl implements DemoRemote{
@Autowired
private DemoConverter demoConverter;
@Autowired
private DemoService demoService;
public DemoModel get(String name){
return demoService.load();
}
public DemoDTO convert(DemoModel model){
return demoConverter.convertToTarget(model);
}
}
package cn.com.glsx.dj.dataprocessing.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.glsx.dj.dataprocessing.mapper.DemoMapper;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
/**
* @Title: DemoService.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
@Service
public class DemoService {
@Autowired
private DemoMapper demoMapper;
public DemoModel load(){
return demoMapper.load();
}
}
package cn.com.glsx.dj.dataprocessing.service;
import cn.com.glsx.dj.dataprocessing.aliyun.AliyunOssFileUploadUtils;
import cn.com.glsx.dj.dataprocessing.aliyun.OssObjectUploadRequestDTO;
import cn.com.glsx.dj.dataprocessing.dto.ReplaceDTO;
import cn.com.glsx.dj.dataprocessing.mapper.PublicDataBackupsMapper;
import cn.com.glsx.dj.dataprocessing.mapper.PublicDataProcessingMapper;
import cn.com.glsx.dj.dataprocessing.model.PublicDataBackups;
import cn.com.glsx.dj.dataprocessing.model.PublicDataProcessing;
import cn.com.glsx.dj.dataprocessing.util.SqlFileWriterUtil;
import cn.com.glsx.dj.dataprocessing.util.TextUtils;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;
/**
* @Description todo
* @Author yelq
* @Date 2025/5/28-14:15
* @Version 1.0
*/
@Slf4j
@Service
public class PublicDataProcessing1Service {
@Autowired
private PublicDataProcessingMapper publicDataProcessingMapper;
@Autowired
private PublicDataBackupsMapper publicDataBackupsMapper;
@Autowired
private AliyunOssFileUploadUtils aliyunOssFileUploadUtils;
@Autowired
private RestTemplate restTemplate;
@Autowired
private Environment env;
@Autowired
private TaskExecutor executor;
private List<String> sqlList = new ArrayList<>();
/**
* 已经处理过的要排除
*/
private Integer limitId = null;
/**
* 替换文件路径为阿里云oss路径
*
* @param timeSlotStr 执行时间段
*/
public void replaceFileUrl2AliyunOssUrl(String timeSlotStr) throws Exception {
// 根据表配置查询表数据
List<PublicDataProcessing> list = publicDataProcessingMapper.getTableConfig();
if (list == null || list.isEmpty()) {
log.info("没有待完成的配置数据");
return;
}
String endpoint = env.getProperty("aliyun.oss.endpoint");
Assert.notNull(endpoint, "阿里云OSS配置(endpoint)不能为空!");
String keywordStr = env.getProperty("replace.url.match.list");
Assert.notNull(keywordStr, "匹配字符串不能为空!");
String[] keyword = keywordStr.split(",");
for (PublicDataProcessing processing : list) {
if (!checkTimeSlot(timeSlotStr)) {
log.info("不在时间段内不处理");
return;
}
long startTime = System.currentTimeMillis();
try {
processing.setEndpoint(endpoint);
processing.setKeywordList(Arrays.asList(keyword));
if (processing.getTotalCount() == null) {
// 如果还没有总条数,那就先查询总条数
processing.setTotalCount(publicDataProcessingMapper.getTotalCount(processing));
// 初始化完成条数
processing.setEndCount(0);
}
if (processing.getTotalCount() == null || processing.getTotalCount() == 0) {
log.info("没有待处理的数据");
// 更新表统计数据
processing.setComplete((byte) 1);
processing.setUpdatedTime(new Date());
processing.setUpdatedBy("system");
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
continue;
}
updateTableData(processing);
// 更新统计数据
processing.setComplete((byte) 1);
processing.setUpdatedTime(new Date());
processing.setUpdatedBy("system");
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
} catch (Exception e) {
log.error("数据处理失败:{}", e.getMessage(), e);
processing.setComplete((byte) 1);
processing.setUpdatedTime(new Date());
processing.setUpdatedBy("system");
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
}
log.info("{}数据处理完成,耗时:{}", processing, System.currentTimeMillis() - startTime);
log.info("更新sql:{}", sqlList);
// 把更新sql保存起来,到本地文件
if (!sqlList.isEmpty()) {
try {
String filePath = "D:\\data\\sql\\" + processing.getTableName() + "-" + processing.getColumnName() + ".sql";
// 写入SQL文件
SqlFileWriterUtil.writeToSqlFile(sqlList.get(0), filePath);
log.error("SQL文件写入成功");
if (sqlList.size() > 1) {
for (int i = 1; i < sqlList.size(); i++) {
// 追加内容
SqlFileWriterUtil.appendToSqlFile(sqlList.get(i), filePath);
}
}
} catch (Exception e) {
log.error("写入文件时出错: " + e.getMessage());
}
sqlList.clear();
}
}
}
private void updateTableData(PublicDataProcessing processing) {
Integer pageSize = env.getProperty("data.deel.page.size",Integer.class,8);
String endpoint = env.getProperty("aliyun.oss.endpoint");
Assert.notNull(endpoint, "阿里云OSS配置(endpoint)不能为空!");
if (limitId != null) {
processing.setLimitId(limitId);
}
Page<ReplaceDTO> page = PageHelper.startPage(1, pageSize);
publicDataProcessingMapper.getDataByOneConfig(processing);
if (page.getPages() > 1) {
List<ReplaceDTO> result = page.getResult();
Optional<Integer> max = result.stream().map(ReplaceDTO::getPrimaryValue).max(Comparator.comparingInt(o -> o));
max.ifPresent(integer -> limitId = integer);
dataHandler(result, processing, endpoint);
for (int i = 2; i <= page.getPages(); i++) {
// 因为每次处理都会更新表,所以这里每次循环只拿前十条
if (limitId != null) {
processing.setLimitId(limitId);
}
long startTime = System.currentTimeMillis();
Page<ReplaceDTO> page2 = PageHelper.startPage(1, pageSize);
publicDataProcessingMapper.getDataByOneConfig(processing);
long l = System.currentTimeMillis() - startTime;
log.info("分页查询数据,耗时:{}", l);
Optional<Integer> max1 = page2.getResult().stream().map(ReplaceDTO::getPrimaryValue).max(Comparator.comparingInt(o -> o));
max1.ifPresent(integer -> limitId = integer);
dataHandler(page2.getResult(), processing, endpoint);
page2.close();
}
} else {
List<ReplaceDTO> result = page.getResult();
dataHandler(result, processing, endpoint);
}
page.close();
limitId = null;
}
private void dataHandler(List<ReplaceDTO> result, PublicDataProcessing processing, String endpoint) {
if (result == null || result.isEmpty()) return;
List<FutureTask<Boolean>> futureTasks = new ArrayList<>();
// 遍历表数据
for (ReplaceDTO replaceDTO : result) {
try {
uploadUrlAndUpdateTableData(replaceDTO, processing, endpoint);
// 增加完成条数
processing.setEndCount(processing.getEndCount() + 1);
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
} catch (Exception e) {
log.error("替换文件链接异常:{}", e.getMessage(), e);
}
}
}
/**
* 替换文件链接并更新表数据
*
* @param replaceDTO
* @param processing
* @param endpoint
*/
private Boolean uploadUrlAndUpdateTableData(ReplaceDTO replaceDTO, PublicDataProcessing processing, String endpoint) {
replaceDTO.setTableName(processing.getTableName());
replaceDTO.setColumnName(processing.getColumnName());
replaceDTO.setPrimaryKeyName(processing.getPrimaryKeyName());
replaceDTO.setColumnType(processing.getColumnType());
// 获取到文件路径
List<String> links = new ArrayList<>();
List<PublicDataBackups> backupsList = new ArrayList<>();
Map<String, String> linkMap = new HashMap<>();
if (replaceDTO.getColumnType() != null && replaceDTO.getColumnType() == 1) {
links = TextUtils.extractFileLinks(replaceDTO.getOldValue());
if (links.isEmpty()) return true;
links = links.stream().filter(s -> s != null && !s.isEmpty() && !s.contains(endpoint)).collect(Collectors.toList());
if (links.isEmpty()) return true;
} else {
if (StringUtils.isEmpty(replaceDTO.getOldValue())
|| StringUtils.isEmpty(replaceDTO.getOldValue().trim())
|| replaceDTO.getOldValue().contains(endpoint)) {
return true;
}
links.add(replaceDTO.getOldValue());
}
// 上传到阿里云OSS
for (String link : links) {
try {
if (linkMap.containsKey(link)) {
continue;
}
// 判断链接是否已经上传过,如果上传过,直接拿已存在的阿里云链接替换
long l = System.currentTimeMillis();
PublicDataBackups query = new PublicDataBackups();
query.setOldUrl(link);
List<PublicDataBackups> select = publicDataBackupsMapper.select(query);
log.info("查询数据库耗时:{}", System.currentTimeMillis() - l);
if (select != null && !select.isEmpty()) {
linkMap.put(link, select.get(0).getNewUrl());
continue;
}
// 获取rul中的文件名
String link1 = link.replace("http://", "").replace("https://", "");
String fileName = link1.substring(link1.indexOf("/") + 1);
if (!fileName.contains("/")) {
// 如果文件名不包含文件路径,为了避免文件名重复,添加一个随机数
fileName = UUID.randomUUID() + fileName;
}
// 获取文件类型
String fileType = link.substring(link.lastIndexOf(".") + 1);
// bytes 即为文件的字节流
byte[] bytes = null;
try {
bytes = restTemplate.execute(link, HttpMethod.GET, null, response -> {
InputStream inputStream = response.getBody();
return IOUtils.toByteArray(inputStream);
});
} catch (Exception e) {
// 处理异常,例如记录日志或抛出自定义异常
log.error("获取文件URL:{}流异常:{}", link, e.getMessage(), e);
continue;
}
String aliyunUrl = aliyunOssFileUploadUtils.uploadFile(new OssObjectUploadRequestDTO(fileName,
bytes, fileType, null));
linkMap.put(link, aliyunUrl);
if (aliyunUrl != null) {
PublicDataBackups backups = new PublicDataBackups();
backups.setTableName(processing.getTableName());
backups.setColumnName(processing.getColumnName());
backups.setOldUrl(link);
backups.setNewUrl(aliyunUrl);
backups.setCreatedBy("system");
backups.setCreatedTime(new Date());
backups.setDelFlag("N");
backupsList.add(backups);
}
} catch (Exception e) {
log.error("上传文件URL:{}失败:{}", link, e.getMessage(), e);
}
}
// 备份数据
if (!backupsList.isEmpty()) {
publicDataBackupsMapper.insertList(backupsList);
}
if (!linkMap.isEmpty()) {
String updateValue = replaceDTO.getOldValue();
// 替换链接
for (Map.Entry<String, String> entry : linkMap.entrySet()) {
updateValue = updateValue.replace(entry.getKey(), entry.getValue());
}
replaceDTO.setUpdateValue(updateValue);
//更新表数据
// publicDataProcessingMapper.updateTableData(replaceDTO);
}
if (replaceDTO.getUpdateValue() != null && !replaceDTO.getUpdateValue().isEmpty()
&& !replaceDTO.getOldValue().equals(replaceDTO.getUpdateValue())) {
String sql = String.format("UPDATE %s SET %s='%s' WHERE %s='%s';",
replaceDTO.getTableName(), replaceDTO.getColumnName(), replaceDTO.getUpdateValue(), replaceDTO.getPrimaryKeyName(), replaceDTO.getPrimaryValue());
sqlList.add(sql);
}
return true;
}
/**
* 校验当前时间是否是在可执行时间段内
*
* @param timeSlotStr
* @return
*/
public static boolean checkTimeSlot(String timeSlotStr) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date now = sdf.parse(sdf.format(new Date()));
String[] timeSlotArr = timeSlotStr.split(",");
if (timeSlotArr.length != 2) {
throw new RpcServiceException("时间段格式错误");
}
String startTimeStr = timeSlotArr[0];
String limitTimeStr = timeSlotArr[1];
Date startTime = sdf.parse(startTimeStr);
Date limitTime = sdf.parse(limitTimeStr);
if (startTime.after(limitTime)) {
// 设置的开始时间大于限制时间,则限制时间指的是下一天
return now.after(startTime) || now.before(limitTime);
}
return now.after(startTime) && now.before(limitTime);
}
public static void main(String[] args) {
String link = "https://img02.glsx.com.cn/weapp/resource/app-zyzs/media/gac-toyota/1.webp";
String link1 = link.replace("http://", "").replace("https://", "");
String fileName = link1.substring(link1.indexOf("/") + 1);
System.out.println(fileName);
}
}
package cn.com.glsx.dj.dataprocessing.service;
import cn.com.glsx.dj.dataprocessing.aliyun.AliyunOssFileUploadUtils;
import cn.com.glsx.dj.dataprocessing.aliyun.OssObjectUploadRequestDTO;
import cn.com.glsx.dj.dataprocessing.dto.ReplaceDTO;
import cn.com.glsx.dj.dataprocessing.mapper.PublicDataBackupsMapper;
import cn.com.glsx.dj.dataprocessing.mapper.PublicDataProcessingMapper;
import cn.com.glsx.dj.dataprocessing.model.PublicDataBackups;
import cn.com.glsx.dj.dataprocessing.model.PublicDataProcessing;
import cn.com.glsx.dj.dataprocessing.util.TextUtils;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;
/**
* @Description todo
* @Author yelq
* @Date 2025/5/28-14:15
* @Version 1.0
*/
@Slf4j
@Service
public class PublicDataProcessingService {
@Autowired
private PublicDataProcessingMapper publicDataProcessingMapper;
@Autowired
private PublicDataBackupsMapper publicDataBackupsMapper;
@Autowired
private AliyunOssFileUploadUtils aliyunOssFileUploadUtils;
@Autowired
private RestTemplate restTemplate;
@Autowired
private Environment env;
@Autowired
private TaskExecutor executor;
/**
* 已经处理过的要排除
*/
private Integer limitId = null;
/**
* 替换文件路径为阿里云oss路径
*
* @param timeSlotStr 执行时间段
*/
public void replaceFileUrl2AliyunOssUrl(String timeSlotStr) throws Exception {
// 根据表配置查询表数据
List<PublicDataProcessing> list = publicDataProcessingMapper.getTableConfig();
if (list == null || list.isEmpty()) {
log.info("没有待完成的配置数据");
return;
}
String endpoint = env.getProperty("aliyun.oss.endpoint");
Assert.notNull(endpoint, "阿里云OSS配置(endpoint)不能为空!");
String keywordStr = env.getProperty("replace.url.match.list");
Assert.notNull(keywordStr, "匹配字符串不能为空!");
String[] keyword = keywordStr.split(",");
for (PublicDataProcessing processing : list) {
if (!checkTimeSlot(timeSlotStr)) {
log.info("不在时间段内不处理");
return;
}
long startTime = System.currentTimeMillis();
try {
processing.setEndpoint(endpoint);
processing.setKeywordList(Arrays.asList(keyword));
if (processing.getTotalCount() == null) {
// 如果还没有总条数,那就先查询总条数
processing.setTotalCount(publicDataProcessingMapper.getTotalCount(processing));
// 初始化完成条数
processing.setEndCount(0);
}
if (processing.getTotalCount() == null || processing.getTotalCount() == 0) {
log.info("没有待处理的数据");
// 更新表统计数据
processing.setComplete((byte) 1);
processing.setUpdatedTime(new Date());
processing.setUpdatedBy("system");
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
continue;
}
updateTableData(processing);
// 更新统计数据
processing.setComplete((byte) 1);
processing.setUpdatedTime(new Date());
processing.setUpdatedBy("system");
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
} catch (Exception e) {
log.error("数据处理失败:{}", e.getMessage(), e);
processing.setComplete((byte) 1);
processing.setUpdatedTime(new Date());
processing.setUpdatedBy("system");
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
}
log.info("{}数据处理完成,耗时:{}", processing, System.currentTimeMillis() - startTime);
}
}
private void updateTableData(PublicDataProcessing processing) {
Integer pageSize = env.getProperty("data.deel.page.size", Integer.class, 8);
String endpoint = env.getProperty("aliyun.oss.endpoint");
Assert.notNull(endpoint, "阿里云OSS配置(endpoint)不能为空!");
if (limitId != null) {
processing.setLimitId(limitId);
}
Page<ReplaceDTO> page = PageHelper.startPage(1, pageSize);
publicDataProcessingMapper.getDataByOneConfig(processing);
if (page.getPages() > 1) {
List<ReplaceDTO> result = page.getResult();
Optional<Integer> max = result.stream().map(ReplaceDTO::getPrimaryValue).max(Comparator.comparingInt(o -> o));
max.ifPresent(integer -> limitId = integer);
dataHandler(result, processing, endpoint);
for (int i = 2; i <= page.getPages(); i++) {
// 因为每次处理都会更新表,所以这里每次循环只拿前十条
if (limitId != null) {
processing.setLimitId(limitId);
}
long startTime = System.currentTimeMillis();
Page<ReplaceDTO> page2 = PageHelper.startPage(1, pageSize);
publicDataProcessingMapper.getDataByOneConfig(processing);
long l = System.currentTimeMillis() - startTime;
log.info("分页查询数据,耗时:{}", l);
Optional<Integer> max1 = page2.getResult().stream().map(ReplaceDTO::getPrimaryValue).max(Comparator.comparingInt(o -> o));
max1.ifPresent(integer -> limitId = integer);
dataHandler(page2.getResult(), processing, endpoint);
page2.close();
}
} else {
List<ReplaceDTO> result = page.getResult();
dataHandler(result, processing, endpoint);
}
page.close();
limitId = null;
}
private void dataHandler(List<ReplaceDTO> result, PublicDataProcessing processing, String endpoint) {
if (result == null || result.isEmpty()) return;
List<FutureTask<Boolean>> futureTasks = new ArrayList<>();
// 遍历表数据
for (ReplaceDTO replaceDTO : result) {
try {
// 创建有返回值的Callable任务
Callable<Boolean> task = () -> uploadUrlAndUpdateTableData(replaceDTO, processing, endpoint);
FutureTask<Boolean> futureTask = new FutureTask<>(task);
executor.execute(futureTask);
futureTasks.add(futureTask);
// uploadUrlAndUpdateTableData(replaceDTO, processing, endpoint);
// 增加完成条数
processing.setEndCount(processing.getEndCount() + 1);
publicDataProcessingMapper.updateByPrimaryKeySelective(processing);
} catch (Exception e) {
log.error("替换文件链接异常:{}", e.getMessage(), e);
}
}
for (FutureTask<Boolean> futureTask : futureTasks) {
try {
futureTask.get();
} catch (Exception e) {
log.error("替换文件链接异常:{}", e.getMessage(), e);
}
}
}
/**
* 替换文件链接并更新表数据
*
* @param replaceDTO
* @param processing
* @param endpoint
*/
private Boolean uploadUrlAndUpdateTableData(ReplaceDTO replaceDTO, PublicDataProcessing processing, String endpoint) {
replaceDTO.setTableName(processing.getTableName());
replaceDTO.setColumnName(processing.getColumnName());
replaceDTO.setPrimaryKeyName(processing.getPrimaryKeyName());
replaceDTO.setColumnType(processing.getColumnType());
// 获取到文件路径
List<String> links = new ArrayList<>();
List<PublicDataBackups> backupsList = new ArrayList<>();
Map<String, String> linkMap = new HashMap<>();
if (replaceDTO.getColumnType() != null && replaceDTO.getColumnType() == 1) {
links = TextUtils.extractFileLinks(replaceDTO.getOldValue());
if (links.isEmpty()) return true;
links = links.stream().filter(s -> s != null && !s.isEmpty() && !s.contains(endpoint)).collect(Collectors.toList());
if (links.isEmpty()) return true;
} else {
if (StringUtils.isEmpty(replaceDTO.getOldValue())
|| StringUtils.isEmpty(replaceDTO.getOldValue().trim())
|| replaceDTO.getOldValue().contains(endpoint)) {
return true;
}
links.add(replaceDTO.getOldValue());
}
// 上传到阿里云OSS
for (String link : links) {
try {
if (linkMap.containsKey(link)) {
continue;
}
// 判断链接是否已经上传过,如果上传过,直接拿已存在的阿里云链接替换
long l = System.currentTimeMillis();
PublicDataBackups query = new PublicDataBackups();
query.setOldUrl(link);
List<PublicDataBackups> select = publicDataBackupsMapper.select(query);
log.info("查询数据库耗时:{}", System.currentTimeMillis() - l);
if (select != null && !select.isEmpty()) {
linkMap.put(link, select.get(0).getNewUrl());
continue;
}
// 获取rul中的文件名
String link1 = link.replace("http://", "").replace("https://", "");
String fileName = link1.substring(link1.indexOf("/") + 1);
if (!fileName.contains("/")) {
// 如果文件名不包含文件路径,为了避免文件名重复,添加一个随机数
fileName = UUID.randomUUID() + fileName;
}
// 获取文件类型
String fileType = link.substring(link.lastIndexOf(".") + 1);
// bytes 即为文件的字节流
byte[] bytes = null;
try {
bytes = restTemplate.execute(link, HttpMethod.GET, null, response -> {
InputStream inputStream = response.getBody();
return IOUtils.toByteArray(inputStream);
});
} catch (Exception e) {
// 处理异常,例如记录日志或抛出自定义异常
log.error("获取文件URL:{}流异常:{}", link, e.getMessage(), e);
continue;
}
String aliyunUrl = aliyunOssFileUploadUtils.uploadFile(new OssObjectUploadRequestDTO(fileName,
bytes, fileType, null));
linkMap.put(link, aliyunUrl);
if (aliyunUrl != null) {
PublicDataBackups backups = new PublicDataBackups();
backups.setTableName(processing.getTableName());
backups.setColumnName(processing.getColumnName());
backups.setOldUrl(link);
backups.setNewUrl(aliyunUrl);
backups.setCreatedBy("system");
backups.setCreatedTime(new Date());
backups.setDelFlag("N");
backupsList.add(backups);
}
} catch (Exception e) {
log.error("上传文件URL:{}失败:{}", link, e.getMessage(), e);
}
}
// 备份数据
if (!backupsList.isEmpty()) {
publicDataBackupsMapper.insertList(backupsList);
}
if (!linkMap.isEmpty()) {
String updateValue = replaceDTO.getOldValue();
// 替换链接
for (Map.Entry<String, String> entry : linkMap.entrySet()) {
updateValue = updateValue.replace(entry.getKey(), entry.getValue());
}
replaceDTO.setUpdateValue(updateValue);
//更新表数据
publicDataProcessingMapper.updateTableData(replaceDTO);
}
return true;
}
/**
* 校验当前时间是否是在可执行时间段内
*
* @param timeSlotStr
* @return
*/
public static boolean checkTimeSlot(String timeSlotStr) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date now = sdf.parse(sdf.format(new Date()));
String[] timeSlotArr = timeSlotStr.split(",");
if (timeSlotArr.length != 2) {
throw new RpcServiceException("时间段格式错误");
}
String startTimeStr = timeSlotArr[0];
String limitTimeStr = timeSlotArr[1];
Date startTime = sdf.parse(startTimeStr);
Date limitTime = sdf.parse(limitTimeStr);
if (startTime.after(limitTime)) {
// 设置的开始时间大于限制时间,则限制时间指的是下一天
return now.after(startTime) || now.before(limitTime);
}
return now.after(startTime) && now.before(limitTime);
}
public static void main(String[] args) {
String link = "https://img02.glsx.com.cn/weapp/resource/app-zyzs/media/gac-toyota/1.webp";
String link1 = link.replace("http://", "").replace("https://", "");
String fileName = link1.substring(link1.indexOf("/") + 1);
System.out.println(fileName);
}
}
package cn.com.glsx.dj.dataprocessing.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
/**
* @Description todo
* @Author yelq
* @Date 2025/7/10-11:06
* @Version 1.0
*/
public class SqlFileWriterUtil {
/**
* 将字符串内容写入到指定的SQL文件中
*
* @param content 要写入的SQL内容
* @param filePath 目标文件路径(如:/path/to/name.sql)
* @throws IOException 如果写入文件时发生错误
*/
public static void writeToSqlFile(String content, String filePath) throws IOException {
writeToSqlFile(content, filePath, StandardCharsets.UTF_8);
}
/**
* 将字符串内容写入到指定的SQL文件中(可指定编码)
*
* @param content 要写入的SQL内容
* @param filePath 目标文件路径
* @param charset 文件编码
* @throws IOException 如果写入文件时发生错误
*/
public static void writeToSqlFile(String content, String filePath, java.nio.charset.Charset charset)
throws IOException {
// 检查参数
if (content == null) {
throw new IllegalArgumentException("Content cannot be null");
}
if (filePath == null || filePath.trim().isEmpty()) {
throw new IllegalArgumentException("File path cannot be null or empty");
}
File file = new File(filePath);
// 创建父目录(如果不存在)
File parentDir = file.getParentFile();
if (parentDir != null && !parentDir.exists()) {
parentDir.mkdirs();
}
// 使用try-with-resources确保资源正确关闭
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(file),
charset))) {
writer.write(content);
writer.flush();
}
}
/**
* 将字符串内容追加到指定的SQL文件中
*
* @param content 要追加的SQL内容
* @param filePath 目标文件路径
* @throws IOException 如果写入文件时发生错误
*/
public static void appendToSqlFile(String content, String filePath) throws IOException {
appendToSqlFile(content, filePath, StandardCharsets.UTF_8);
}
/**
* 将字符串内容追加到指定的SQL文件中(可指定编码)
*
* @param content 要追加的SQL内容
* @param filePath 目标文件路径
* @param charset 文件编码
* @throws IOException 如果写入文件时发生错误
*/
public static void appendToSqlFile(String content, String filePath, java.nio.charset.Charset charset)
throws IOException {
// 检查参数
if (content == null) {
throw new IllegalArgumentException("Content cannot be null");
}
if (filePath == null || filePath.trim().isEmpty()) {
throw new IllegalArgumentException("File path cannot be null or empty");
}
File file = new File(filePath);
// 如果文件不存在,则创建
if (!file.exists()) {
writeToSqlFile(content, filePath, charset);
return;
}
// 使用try-with-resources确保资源正确关闭
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(file, true), // true表示追加模式
charset))) {
writer.write(content);
writer.newLine(); // 追加新行
writer.flush();
}
}
}
package cn.com.glsx.dj.dataprocessing.util;
import cn.com.glsx.dj.dataprocessing.dto.ReplaceDTO;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Description 文本工具类
* @Author yelq
* @Date 2025/5/28-14:22
* @Version 1.0
*/
public class TextUtils {
/**
* 从文本中提取符合要求的文件链接
*
* @param text 输入文本
* @return 匹配的链接列表
*/
public static List<String> extractFileLinks(String text) {
List<String> links = new ArrayList<>();
if (text == null|| text.isEmpty())return links;
// 正则表达式匹配:
// 1. 以http或https开头
// 2. 中间任意字符(非贪婪模式)
// 3. 以常见文件后缀结尾(不区分大小写)
String regex = "(?i)\\bhttps?://\\S+?\\.(?:pdf|jpg|jpeg|png|gif|bmp|docx?|xlsx?|pptx?|zip|rar|7z|txt|csv|mp3|mp4|avi|mov)\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
links.add(matcher.group());
}
return links;
}
}
package cn.com.glsx.dj.dataprocessing.util;
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.dataprocessing.mapper.DemoMapper">
<select id="load" resultType="cn.com.glsx.dj.dataprocessing.model.DemoModel">
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.dataprocessing.mapper.PublicDataBackupsMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.dataprocessing.model.PublicDataBackups">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="table_name" jdbcType="VARCHAR" property="tableName" />
<result column="column_name" jdbcType="VARCHAR" property="columnName" />
<result column="old_url" jdbcType="VARCHAR" property="oldUrl" />
<result column="new_url" jdbcType="VARCHAR" property="newUrl" />
<result column="created_by" jdbcType="VARCHAR" property="createdBy" />
<result column="created_time" jdbcType="TIMESTAMP" property="createdTime" />
<result column="updated_by" jdbcType="VARCHAR" property="updatedBy" />
<result column="updated_time" jdbcType="TIMESTAMP" property="updatedTime" />
<result column="del_flag" jdbcType="CHAR" property="delFlag" />
</resultMap>
<sql id="Base_Column_List">
id, table_name, column_name, old_url, new_url, created_by, created_time, updated_by,
updated_time, del_flag
</sql>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.glsx.dj.dataprocessing.mapper.PublicDataProcessingMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.dataprocessing.model.PublicDataProcessing">
<!--
WARNING - @mbg.generated
-->
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="table_name" property="tableName" jdbcType="VARCHAR"/>
<result column="primary_key_name" property="primaryKeyName" jdbcType="VARCHAR"/>
<result column="column_name" property="columnName" jdbcType="VARCHAR"/>
<result column="column_type" property="columnType" jdbcType="INTEGER"/>
<result column="total_count" property="totalCount" jdbcType="INTEGER"/>
<result column="end_count" property="endCount" jdbcType="INTEGER"/>
<result column="complete" property="complete" jdbcType="TINYINT"/>
<result column="created_by" property="createdBy" jdbcType="VARCHAR"/>
<result column="created_time" property="createdTime" jdbcType="TIMESTAMP"/>
<result column="updated_by" property="updatedBy" jdbcType="VARCHAR"/>
<result column="updated_time" property="updatedTime" jdbcType="TIMESTAMP"/>
<result column="del_flag" property="delFlag" jdbcType="CHAR"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, table_name, primary_key_name, column_name, column_type, total_count, end_count, complete, created_by, created_time,
updated_by,
updated_time, del_flag
</sql>
<update id="updateTableData">
UPDATE ${tableName} SET ${columnName}=#{updateValue} WHERE ${primaryKeyName}=#{primaryValue}
</update>
<select id="getTableConfig" resultMap="BaseResultMap">
SELECT * FROM `public_data_procesing` WHERE del_flag='N' AND complete=0
</select>
<select id="getDataByOneConfig" resultType="cn.com.glsx.dj.dataprocessing.dto.ReplaceDTO">
SELECT ${columnName} oldValue,${primaryKeyName} primaryValue FROM ${tableName}
<where>
${columnName} NOT REGEXP #{endpoint} AND
<foreach collection="keywordList" item="keyword" separator="OR" open="(" close=")">
${columnName} REGEXP #{keyword}
</foreach>
<if test="limitId != null">
AND ${primaryKeyName} &gt; #{limitId}
</if>
</where>
ORDER BY ${primaryKeyName} ASC
</select>
<select id="getTotalCount" resultType="java.lang.Integer">
SELECT COUNT(*) FROM ${tableName}
<where>
${columnName} NOT REGEXP #{endpoint} AND
<foreach collection="keywordList" item="keyword" separator="OR" open="(" close=")">
${columnName} REGEXP #{keyword}
</foreach>
</where>
</select>
</mapper>
\ No newline at end of file
# framework-archetype-rpc
RPC服务项目骨架
```properties
└─src
├─main
├─java
├─cn.com.glsx.dj.dataprocessing.config 配置层
├─cn.com.glsx.dj.dataprocessing.manager 通用处理层
├─cn.com.glsx.dj.dataprocessing.mapper Dao映射层
├─cn.com.glsx.dj.dataprocessing.remote RPC接口实现层
├─cn.com.glsx.dj.dataprocessing.service 业务层
├─cn.com.glsx.dj.dataprocessing.util 工具包
└─cn.com.glsx.dj.dataprocessing.Main.java 程序入口
├─resources 资源文件目录
├─config
├─application.properties 应用配置文件
├─META-INF
└─orm SQL配置文件
├─templates 模板目录
└─*.flt freemarker模板,(可用于邮件模板)
└─logback.xml 日志配置文件
└─webapp web前端文件目录
└─WEB-INF
└─bin shell脚本文件(包含启动、停止、重启等)
└─test 测试目录
├─java
└─cn.com.glsx.dj.dataprocessing/service 测试代码
└─resources 测试资源目录
└─pom.xml pom文件
```
二、使用说明:
```properties
1、运行项目前需在配置中心创建配置信息,配置内容参考三配置说明:
1.1> dataId : application.properties --> ore.diamond.dataId + ore.diamond.env
1.2> group : application.properties --> ore.diamond.group
1.3> content : 参考三配置说明
2、生成mybatis文件的插件,使用说明:
1.1> 生成之后可以删掉插件
1.2> IDEA内:点击右侧Maven Projects > 项目 plugins > mybatis-generator 运行
1.3> ECLIPSE内:右键点击项目,选择RUN AS maven build > 输入maven命令:
mybatis-generator:generate -e > 运行
3、Bean转换器mapstruct使用说明:
1.1> 在converter包内建立Bean转换对应的转换器,传入source和target的类型。
1.2> 在remote内使用spring的方式引入bean。
1.3> Bean的属性名一样的情况下,不需要重写方法。
4、自定义过滤器加入方式:
1.1> 在src.main.resources.META-INF.dubbo文件夹下新建文件com.alibaba.dubbo.rpc.Filter
1.2> 在该文件内写入自定义过滤器类的完整地址,以键值对的形式加入,左边为key名称,例如:
dubboAuthorizeFilter=cn.com.glsx.payment.roof.filter.DubboAuthorizeFilter
1.3> 在钻石配置中加入dubbo过滤器的配置,名字为key,例如:
ore.dubbo.provider.enabled=true
ore.dubbo.provider.filter=dubboAuthorizeFilter
```
```properties
#----------------------------------------------------------------------------------------------------------
# dubbo配置
# dubbo应用名称
ore.dubbo.application.name=rpc-dj-dataprocessing
# dubbo应用所有者
ore.dubbo.application.owner=deployer name
# dubbo服务注册地址
ore.dubbo.registry.address=zookeeper://192.168.3.206:2181
# dubbo服务注册超时时间
ore.dubbo.registry.timeout=30000
# 默认协议:dubbo
ore.dubbo.protocol.name=dubbo
# dubbo服务扫描包路径
ore.dubbo.scan=cn.com.glsx.dj.dataprocessing.remote
# dubbo服务监控
ore.dubbo.monitor.protocol=registry
# dubbo服务统计
ore.dubbo.provider.filter=metrics
# dubbo配置中心
ore.dubbo.config-center.address=zookeeper://192.168.3.206:2181
# dubbo元数据中心
ore.dubbo.metadata-report.address=zookeeper://192.168.3.206:2181
┌------------------------------------------------------------┐
注:如需在RPC服务里面支持REST风格的服务
1、需在pom中添加如下依赖:
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-dubbo-rest</artifactId>
</dependency>
2、修改钻石配置
# dubbo协议配置(二选一)
#ore.dubbo.protocol.name=dubbo
#ore.dubbo.protocol.port=20880
# dubbo协议配置(二选一)
ore.dubbo.protocols.dubbo.name=dubbo
ore.dubbo.protocols.dubbo.port=20880
# REST协议配置
ore.dubbo.protocols.rest.name=rest
# 应用服务器(默认jetty)
ore.dubbo.protocols.rest.server=jetty
# 服务端口
ore.dubbo.protocols.rest.port=8080
# 最大连接数
ore.dubbo.protocols.rest.accepts=500
# 线程池大小
ore.dubbo.protocols.rest.threads=100
# 基础相对路径
ore.dubbo.protocols.rest.contextpath=rest-api
3、Java示例代码:
@Service //dubbo注解,注册服务
@Path("users") //JAX-RS注解
public class UserServiceRemoteImpl implements UserServiceRemote {
@POST //JAX-RS注解
@Path("register") //JAX-RS注解
@Consumes({MediaType.APPLICATION_JSON}) //JAX-RS注解
public void registerUser(User user) {
// save the user...
}
}
4、访问示例:
http://localhost:8080/rest-api/users/register
5、参考资料
resteasy框架使用介绍,参阅官方文档,地址:http://docs.jboss.org/resteasy/docs/3.6.0.Final/userguide/html/index.html
dubbo rest协议说明,参阅官方文档,地址:http://dubbo.apache.org/zh-cn/docs/user/references/protocol/rest.html
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# druid连接池及数据源配置
ore.druid.url=jdbc:mysql://host:port/数据库名?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
ore.druid.driver-class=com.mysql.jdbc.Driver
ore.druid.username=用户名
ore.druid.password=密码
ore.druid.initial-size=1
ore.druid.min-idle=1
ore.druid.max-active=20
ore.druid.test-on-borrow=true
# druid连接池监控配置
# 是否开启监控
ore.druid.monitor.enabled=true
# 监控后台用户名,默认:admin
ore.druid.monitor.login-username=admin
# 监控后台密码,默认:admin123
ore.druid.monitor.login-password=admin123
# 监控访问路径匹配规则,默认:/druid/*
ore.druid.monitor.url-mappings=/druid/*
# 监控访问IP白名单,多个以英文逗号“,”隔开,默认:127.0.0.1
ore.druid.monitor.allow=127.0.0.1
# 监控访问IP黑名单(存在共同时,deny优先于allow),多个以英文逗号“,”隔开
ore.druid.monitor.deny=192.168.0.1
# 是否能够重置数据,默认:false,则隐藏页面重置按钮
ore.druid.monitor.reset-enable=false
# 开启SQL监控
ore.druid.filter.stat.enabled=true
# 数据库类型
ore.druid.filter.stat.db-type=mysql
# 是否合并sql
ore.druid.filter.stat.merge-sql=true
# 是否记录慢查询
ore.druid.filter.stat.log-slow-sql=true
# 慢查询时间:200毫秒(默认3000毫秒)
ore.druid.filter.stat.slow-sql-millis=200
# 开启日志监控
ore.druid.filter.slf4j.enabled=true
ore.druid.filter.slf4j.data-source-log-enabled=true
ore.druid.filter.slf4j.statement-executable-sql-log-enable=true
# 开启Spring监控
ore.druid.monitor.spring.enabled=true
# 扫描的包路径,可配置多个,以逗号‘,’隔开
ore.druid.monitor.scanPackages=cn.com.glsx.dj.dataprocessing.mapper.*,cn.com.glsx.dj.dataprocessing.service.*
┌------------------------------------------------------------┐
注:如需使用SQL监控需在pom中添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# mybatis配置
# 实体模型包
mybatis.type-aliases-package=cn.com.glsx.dj.dataprocessing.model
# SQL脚本文件路径
mybatis.mapper-locations=classpath:/META-INF/orm/*Mapper.xml
# 开启mybatis sql打印
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mapper.mappers=org.oreframework.datasource.mybatis.mapper.OreMapper
mapper.not-empty=false
mapper.identity=MYSQL
# 多数据源配置(主库/读写)
#----------------------------------------------------------------------------------------------------------
# druid连接池及数据源配置
ore.primary.druid.url=jdbc:mysql://主库host:主库port/数据库名?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
ore.primary.druid.driver-class=com.mysql.jdbc.Driver
ore.primary.druid.username=用户名
ore.primary.druid.password=密码
ore.primary.druid.initial-size=1
ore.primary.druid.min-idle=1
ore.primary.druid.max-active=20
ore.primary.druid.test-on-borrow=true
# mybatis配置
# 实体模型包
ore.primary.mybatis.type-aliases-package=cn.com.glsx.dj.dataprocessing.model
# SQL脚本文件路径
ore.primary.mybatis.mapper-locations=classpath:/META-INF/orm/*Mapper.xml
ore.primary.mapper.mappers=org.oreframework.datasource.mybatis.mapper.OreMapper
ore.primary.mapper.not-empty=false
ore.primary.mapper.identity=MYSQL
┌------------------------------------------------------------┐
使用说明:
方式一:
1、引入SqlSessionTemplate
@Resource(name = "primarySqlSessionTemplate")
private SqlSessionTemplate primarySqlSessionTemplate;
2、获取XxMapper
XxMapper mapper = primarySqlSessionTemplate.getMapper(XxMapper.class);
3、调用
mapper.insert(record);
mapper.delete(record);
......
方式二:
1、XxMapper类上添加注解@PrimaryMapper
2、普通方式调用
└------------------------------------------------------------┘
# 多数据源配置(从库/只读)
#----------------------------------------------------------------------------------------------------------
# druid连接池及数据源配置
ore.secondary.druid.url=jdbc:mysql://从库host:从库port/数据库名?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
ore.secondary.druid.driver-class=com.mysql.jdbc.Driver
ore.secondary.druid.username=用户名
ore.secondary.druid.password=密码
ore.secondary.druid.initial-size=1
ore.secondary.druid.min-idle=1
ore.secondary.druid.max-active=20
ore.secondary.druid.test-on-borrow=true
# mybatis配置
# 实体模型包
ore.secondary.mybatis.type-aliases-package=cn.com.glsx.dj.dataprocessing.model
# SQL脚本文件路径
ore.secondary.mybatis.mapper-locations=classpath:/META-INF/orm/*Mapper.xml
ore.secondary.mapper.mappers=org.oreframework.datasource.mybatis.mapper.OreMapper
ore.secondary.mapper.not-empty=false
ore.secondary.mapper.identity=MYSQL
┌------------------------------------------------------------┐
使用说明:
方式一:
1、引入SqlSessionTemplate
@Resource(name = "secondarySqlSessionTemplate")
private SqlSessionTemplate secondarySqlSessionTemplate;
2、获取XxMapper
XxMapper mapper = secondarySqlSessionTemplate.getMapper(XxMapper.class);
3、调用
mapper.insert(record);
mapper.delete(record);
......
方式二:
1、XxMapper类上添加注解@SecondaryMapper
2、普通方式调用
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# 分页配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
#----------------------------------------------------------------------------------------------------------
# Dubbo Swagger配置
# 是否启用swagger-dubbo,默认为true
swagger.dubbo.enable=true
# http请求地址,默认为http://ip:port/h/com.XXX.XxService/method
#swagger.dubbo.http=h
# rpc zk调用 or 本地调用,默认为rpc
#swagger.dubbo.cluster=rpc
# dubbo 服务版本号,可不配置
swagger.dubbo.application.version=1.0-SNAPSHOT
# dubbo服务groupId,可不配置
swagger.dubbo.application.groupId=cn.com.glsx.dj.dataprocessing
# dubbo服务artifactId,可不配置
swagger.dubbo.application.artifactId=rpc-dj-dataprocessing
┌------------------------------------------------------------┐
使用说明:
1、接口或实现类的方法上添加Swagger注解@ApiOperation(nickname = "queryBy**", value = "查询**", notes = "根据**查询**", httpMethod="GET")[非必须]
2、接口参数添加Swagger注解@ApiParam(value = "参数名称", required=true)[非必须]
3、对象属性添加Swagger注解@ApiModelProperty(value = "属性名称")[非必须]
注意事项:
1、对于服务接口方法重载,为了在http请求中唯一确认一个方法,需要使用注解@ApiOperation(nickname = "byId"),通过nickname标记唯一路径(如果不填写,将只显示一个方法)。
此时,rest的请求地址为:http://ip:port/h/com.XXX.XxService/method/byId
2、Object对象作为http请求参数为json string格式
3、swagger注解既可以写在接口上,也可以写在实现类上
4、原生类型作为http请求参数为必填
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# Freemarker模板配置
# 模板存放路径
spring.freemarker.template-loader-path=classpath:/templates/
# 是否开启模板缓存,默认是开启,开发时请关闭
spring.freemarker.cache=false
# 模板的编码设置,默认UTF-8
spring.freemarker.charset=UTF-8
# 是否检测模板已存在本地
spring.freemarker.check-template-location=true
# 模板的媒体类型设置,默认为text/html
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
# 后缀设置,默认为.ftl
spring.freemarker.suffix=.ftl
┌------------------------------------------------------------┐
注:如需使用freemarker需在pom中添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# kafka生产者配置
spring.kafka.producer.metadata.broker.list=192.168.3.207:9092
spring.kafka.producer.topic=消息主题
spring.kafka.producer.serializer.class=kafka.serializer.DefaultEncoder
spring.kafka.producer.type=async
spring.kafka.producer.request.required.acks=1
┌------------------------------------------------------------┐
注:如需使用kafka发送消息需在pom中添加如下依赖
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-jms</artifactId>
</dependency>
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# kafka消费者配置
spring.kafka.consumer.group.id=rpc-dj-dataprocessing-consumer
spring.kafka.consumer.zookeeper.connect=192.168.3.207:2181
spring.kafka.consumer.zookeeper.connection.timeout.ms=15000
spring.kafka.consumer.zookeeper.session.timeout.ms=15000
spring.kafka.consumer.auto.commit.interval.ms=1000
spring.kafka.consumer.auto.offset.reset=largest
spring.kafka.consumer.topic=消息主题
# 默认分区消费线程数
spring.kafka.consumer.partitionsNum=6
# 指定主题分区消费线程数
spring.kafka.consumer.消息主题.partitionsNum=2
┌------------------------------------------------------------┐
注:如需使用kafka接收消息需在pom中添加如下依赖
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-jms</artifactId>
</dependency>
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# redis配置
ore.redis.hostName=192.168.3.207
ore.redis.port=6379
ore.redis.password=
ore.redis.pool.maxActive=600
ore.redis.pool.maxWait=10000
ore.redis.pool.maxTotal=300
ore.redis.pool.maxIdle=300
ore.redis.pool.minIdle=0
ore.redis.timeout=30000
┌------------------------------------------------------------┐
注:如需使用redis,需在pom中添加如下依赖
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-redis</artifactId>
</dependency>
└------------------------------------------------------------┘
#----------------------------------------------------------------------------------------------------------
# 雪花算法
# 开启雪花算法
ore.snowflake.enabled=true
# 数据中心ID(0~31)
ore.snowflake.data-center-id=1
# 工作节点ID(0~31)
ore.snowflake.worker-id=1
┌------------------------------------------------------------┐
使用说明:
1、注入SnowflakeWorker
@Autowired
private SnowflakeWorker snowflakeWorker;
2、调用本地方法
long randomId = snowflakeWorker.nextId();
└------------------------------------------------------------┘
```
```properties
增加配置本地静态类获取:OrePropertyConfigurer
获取示例: String url = OrePropertyConfigurer.getString("ore.druid.url");
Integer maxActive = OrePropertyConfigurer.getInteger("ore.druid.max-active");
```
server.port=11024
server.display-name=rpc-dj-dataprocessing
server.servlet.context-path=/rpc-dj-dataprocessing
server.servlet.application-display-name=rpc-dj-dataprocessing
logging.config=classpath:logback.xml
logging.path=/data/java_log/jetty/rpc-dj-dataprocessing/rpc-dj-dataprocessing.log
logging.level.root=INFO
ore.starter.class-name=Main
# diamond config
ore.diamond.group=ddh
ore.diamond.dataId=rpc-dj-dataprocessing
ore.diamond.env=release
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property resource="config/application.properties" />
<property name="APP_NAME" value="${server.display-name}" />
<property name="LOG_PATH" value="${logging.path}" />
<property name="LOG_LEVEL" value="${logging.level}" />
<contextName>${APP_NAME}</contextName>
<turboFilter class="org.oreframework.boot.logging.logback.OreBootTurboFilter">
<Marker>oreframework</Marker>
</turboFilter>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="org.oreframework.commons.log.OrePatternLayout">
<pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [${APP_NAME}] [%traceid] [%thread] %-5level [%logger{36}.%method %line] - %msg%n</pattern>
</pattern>
</layout>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- <Encoding> Label Old version of this label can not be used -->
<!-- <Encoding>UTF-8</Encoding> -->
<File>${LOG_PATH}</File>
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> -->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<FileNamePattern>${LOG_PATH}.%d{yyyy-MM-dd}.%i</FileNamePattern>
<MaxHistory>15</MaxHistory>
<maxFileSize>200MB</maxFileSize>
</rollingPolicy>
<layout class="org.oreframework.commons.log.OrePatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [${APP_NAME}] [%traceid] [%thread] %-5level [%logger{36}.%method %line] - %msg%n</pattern>
</layout>
<!-- 根据文件大小滚动,不支持 SizeBasedTriggeringPolicy 这种配置-->
<!-- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>200MB</MaxFileSize>
</triggeringPolicy> -->
</appender>
<!-- druid连接池慢查询日志记录 -->
<appender name="DruidFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${LOG_PATH}.druid_slow_sql</file>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 归档的日志文件的路径,例如今天是2020-01-01日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
而2020-01-01的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
<fileNamePattern>${LOG_PATH}.druid_slow_sql-%d{yyyy-MM-dd}.%i</fileNamePattern>
<!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始,命名日志文件,例如log-error-2020-01-01.0.log -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>200MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<!-- 追加方式记录日志 -->
<append>true</append>
<!-- 日志文件的格式 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!-- 此日志文件只记录级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<root level="${LOG_LEVEL}">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
<appender-ref ref="DruidFILE" />
</root>
</configuration>
\ No newline at end of file
此程序是为了处理原始链接不是阿里云的数据,将原始链接替换为阿里云链接。
使用步骤:
### 1、更换程序数据库链接配置[用于连接需要替换的数据库]
```markdown
ore.druid.url=jdbc:mysql://ip:
port/数据库?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
ore.druid.username=用户名
ore.druid.password=密码
```
### 2、更换阿里云配置[用于区分业务]
```markdown
#阿里云OSS配置(测试开发环境,如果使用了预览域名,则使用http,生产用https)
aliyun.oss.base.url=https://
aliyun.oss.endpoint=oss-cn-shenzhen.aliyuncs.com
aliyun.oss.accessKeyId=
aliyun.oss.accessKeySecret=
aliyun.oss.bucketName.fastdfs.default=
#内网上传开关(1-开启,0-关闭)
aliyun.oss.endpoint.intranet.flag=1
#内网Endpoint(地域节点)
aliyun.oss.endpoint.intranet=oss-cn-shenzhen-internal.aliyuncs.com
#预览模式(0-关闭,1-开启)
aliyun.oss.endpoint.preview.flag=1
#预览模式域名
aliyun.oss.endpoint.preview=dj-oss-fastdfs.glsx.com.cn
#每页处理数据量
data.deel.page.size=80
```
### 3、查询关键字配置[用于查询原始链接]
```markdown
# 匹配关键字
replace.url.match.list=qcimg01.glsx.com.cn,wx.glsx.com.cn,bhg.didihu.com.cn,bhg.hhxtechnology.com,img01.glsx.com.cn,img02.glsx.com.cn,scrm.glsx.com.cn
# 执行时间08:00之后,第二天05:00之前执行
aliyun.oss.url.replace.time.slot=08:00,05:00
# 内网上传开关(1-开启,0-关闭)
aliyun.oss.endpoint.intranet.flag=0
# 内网Endpoint(地域节点)
aliyun.oss.endpoint.intranet=oss-cn-shenzhen-internal.aliyuncs.com
```
### 4、初始化配置表和备份表
```sql
CREATE TABLE `public_data_procesing` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`table_name` varchar(64) DEFAULT NULL COMMENT '表名',
`primary_key_name` varchar(64) DEFAULT NULL COMMENT '主键字段名',
`column_name` varchar(64) DEFAULT NULL COMMENT '字段名',
`column_type` int(1) DEFAULT NULL COMMENT '字段类型:0-简单文件链接,1-文本字符串含有多个文件链接',
`total_count` int(11) DEFAULT NULL COMMENT '总条数',
`end_count` int(11) DEFAULT NULL COMMENT '已完成条数',
`complete` tinyint(1) DEFAULT NULL COMMENT '是否完成(0-未完成;1-已完成)',
`created_by` varchar(64) DEFAULT NULL COMMENT '创建人',
`created_time` datetime DEFAULT NULL COMMENT '创建时间',
`updated_by` varchar(64) DEFAULT NULL COMMENT '修改人',
`updated_time` datetime DEFAULT NULL COMMENT '修改时间',
`del_flag` char(1) DEFAULT 'N' COMMENT '删除标识(Y:已删除;N:未删除)',
PRIMARY KEY (`id`),
KEY `idx_table_name` (`table_name`),
KEY `idx_column_name` (`column_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='公共数据处理表';
CREATE TABLE `public_data_backups` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`table_name` varchar(64) DEFAULT NULL COMMENT '表名',
`column_name` varchar(64) DEFAULT NULL COMMENT '字段名',
`old_url` varchar(255) DEFAULT NULL COMMENT '旧链接',
`new_url` varchar(255) DEFAULT NULL COMMENT '新链接',
`created_by` varchar(64) DEFAULT NULL COMMENT '创建人',
`created_time` datetime DEFAULT NULL COMMENT '创建时间',
`updated_by` varchar(64) DEFAULT NULL COMMENT '修改人',
`updated_time` datetime DEFAULT NULL COMMENT '修改时间',
`del_flag` char(1) DEFAULT 'N' COMMENT '删除标识(Y:已删除;N:未删除)',
PRIMARY KEY (`id`),
KEY `idx_table_name` (`table_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='公共数据处理旧数据备份表';
-- 示例配置
INSERT INTO `public_data_procesing` (`table_name`,
`primary_key_name`, `column_name`, `column_type`, `total_count`, `end_count`,
`complete`, `created_by`, `created_time`, `updated_by`, `updated_time`, `del_flag`)
VALUES ('early_warning_error', 'id', 'error_msg', '0', NULL, NULL, '0',
'admin', '2025-06-30 19:07:34', 'system', '2025-06-30 21:00:48', 'N');
```
### 5、执行自动任务程序:AliyunOSSUrlReplaceFastdfsUrlJob,观察配置表(public_data_procesing)统计数据是否有变化
\ No newline at end of file
#!/bin/bash
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
DEPLOY_DIR=`pwd`
CONF_DIR=$DEPLOY_DIR/classes
SERVER_NAME=`sed '/application.name/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
#LOGS_FILE=`sed '/log4j.appender.logToFile.File/!d;s/.*=//' classes/log4j.properties | tr -d '\r'`
LOGS_FILE=`sed '/name="LOG_PATH"/!d;s/.*value="\(.*\)".*/\1/g' classes/logback.xml`
if [ -z "$SERVER_NAME" ]; then
SERVER_NAME=`hostname`
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -z "$PIDS" ]; then
echo "ERROR: The $SERVER_NAME does not started!"
exit 1
fi
LOGS_DIR=""
if [ -n "$LOGS_FILE" ]; then
LOGS_DIR=`dirname $LOGS_FILE`
else
LOGS_DIR=$DEPLOY_DIR/logs
fi
if [ ! -d $LOGS_DIR ]; then
mkdir $LOGS_DIR
fi
DUMP_DIR=$LOGS_DIR/dump
if [ ! -d $DUMP_DIR ]; then
mkdir $DUMP_DIR
fi
DUMP_DATE=`date +%Y%m%d%H%M%S`
DATE_DIR=$DUMP_DIR/$DUMP_DATE
if [ ! -d $DATE_DIR ]; then
mkdir $DATE_DIR
fi
echo -e "Dumping the $SERVER_NAME ...\c"
for PID in $PIDS ; do
jstack $PID > $DATE_DIR/jstack-$PID.dump 2>&1
echo -e ".\c"
jinfo $PID > $DATE_DIR/jinfo-$PID.dump 2>&1
echo -e ".\c"
jstat -gcutil $PID > $DATE_DIR/jstat-gcutil-$PID.dump 2>&1
echo -e ".\c"
jstat -gccapacity $PID > $DATE_DIR/jstat-gccapacity-$PID.dump 2>&1
echo -e ".\c"
jmap $PID > $DATE_DIR/jmap-$PID.dump 2>&1
echo -e ".\c"
jmap -heap $PID > $DATE_DIR/jmap-heap-$PID.dump 2>&1
echo -e ".\c"
jmap -histo $PID > $DATE_DIR/jmap-histo-$PID.dump 2>&1
echo -e ".\c"
if [ -r /usr/sbin/lsof ]; then
/usr/sbin/lsof -p $PID > $DATE_DIR/lsof-$PID.dump
echo -e ".\c"
fi
done
if [ -r /bin/netstat ]; then
/bin/netstat -an > $DATE_DIR/netstat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/iostat ]; then
/usr/bin/iostat > $DATE_DIR/iostat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/mpstat ]; then
/usr/bin/mpstat > $DATE_DIR/mpstat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/vmstat ]; then
/usr/bin/vmstat > $DATE_DIR/vmstat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/free ]; then
/usr/bin/free -t > $DATE_DIR/free.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/sar ]; then
/usr/bin/sar > $DATE_DIR/sar.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/uptime ]; then
/usr/bin/uptime > $DATE_DIR/uptime.dump 2>&1
echo -e ".\c"
fi
echo "OK!"
echo "DUMP: $DATE_DIR"
#!/bin/bash
ENV=$1
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
cd `dirname $0`
./stop.sh
./start.sh $ENV
\ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
JAVA_HOME="/app/soft/jdk1.8.0_20"
ENV=$1
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
DEPLOY_DIR=`pwd`
CONF_DIR=$DEPLOY_DIR/classes
SERVER_NAME=`sed '/server.display-name/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
SERVER_PORT=`sed '/server.port/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
#LOGS_FILE=`sed '/log4j.appender.logToFile.File/!d;s/.*=//' classes/log4j.properties | tr -d '\r'`
LOGS_FILE=`sed '/logging.path/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
if [ -z "$SERVER_NAME" ]; then
SERVER_NAME=`hostname`
fi
echo "server name is $SERVER_NAME"
echo "server port is $SERVER_PORT"
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The $SERVER_NAME already started!"
echo "PID: $PIDS"
exit 1
fi
if [ -n "$SERVER_PORT" ]; then
SERVER_PORT_COUNT=`netstat -tln | grep $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The $SERVER_NAME port $SERVER_PORT already used!"
exit 1
fi
fi
LOGS_DIR=""
if [ -n "$LOGS_FILE" ]; then
LOGS_DIR=`dirname $LOGS_FILE`
else
LOGS_DIR=$DEPLOY_DIR/logs
fi
if [ ! -d $LOGS_DIR ]; then
mkdir $LOGS_DIR
fi
STDOUT_FILE=$LOGS_DIR/stdout.log
LIB_DIR=$DEPLOY_DIR/lib
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true "
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
JAVA_MEM_OPTS=""
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting the $SERVER_NAME ...\c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -classpath $CONF_DIR:$LIB_JARS org.oreframework.boot.bootstrap.OreBootApplication env=$ENV > $STDOUT_FILE 2>&1 &
COUNT=0
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
if [ -n "$SERVER_PORT" ]; then
COUNT=`netstat -an | grep $SERVER_PORT | wc -l`
else
COUNT=`ps --no-heading -C java -f --width 1000 | grep "$DEPLOY_DIR" | awk '{print $2}' | wc -l`
fi
if [ $COUNT -gt 0 ]; then
break
fi
done
echo "OK!"
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$DEPLOY_DIR" | awk '{print $2}'`
echo "PID: $PIDS"
echo "STDOUT: $STDOUT_FILE"
#!/bin/bash
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
DEPLOY_DIR=`pwd`
CONF_DIR=$DEPLOY_DIR/classes
SERVER_NAME=`sed '/application.name/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
if [ -z "$SERVER_NAME" ]; then
SERVER_NAME=`hostname`
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -z "$PIDS" ]; then
echo "ERROR: The $SERVER_NAME does not started!"
exit 1
fi
#if [ "$1" != "skip" ]; then
#$BIN_DIR/dump.sh
#fi
echo -e "Stopping the $SERVER_NAME ...\c"
for PID in $PIDS ; do
kill $PID > /dev/null 2>&1
done
COUNT=0
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
for PID in $PIDS ; do
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
COUNT=0
break
fi
done
done
echo "OK!"
echo "PID: $PIDS"
package cn.com.glsx.dj.dataprocessing.remote;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.com.glsx.dj.dataprocessing.Main;
/**
* @Title: BaseRemoteTest.java
* @Description:
* @author deployer name
* @date 2018年1月6日 下午3:58:33
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2015
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
public class BaseRemoteTest {
}
package cn.com.glsx.dj.dataprocessing.remote;
import org.junit.Assert;
import org.junit.Test;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
/**
* @Title: DemoRemoteTest.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
public class DemoRemoteTest extends BaseRemoteTest{
@DubboReference
private DemoRemote demoRemote;
@Test
public void load(){
DemoModel model = demoRemote.get("name");
Assert.assertNotNull(model);
}
}
package cn.com.glsx.dj.dataprocessing.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.com.glsx.dj.dataprocessing.Main;
/**
* @Title: BaseServiceTest.java
* @Description:
* @author deployer name
* @date 2018年1月6日 下午1:23:03
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2015
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
public class BaseServiceTest {
@Test
public void Test() throws Exception {
System.out.println("hello");
}
}
package cn.com.glsx.dj.dataprocessing.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.Assert;
import org.junit.Test;
import cn.com.glsx.dj.dataprocessing.model.DemoModel;
/**
* @Title: DemoServiceTest.java
* @Description:
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2017
*/
public class DemoServiceTest extends BaseServiceTest{
@Autowired
private DemoService demoService;
@Test
public void load(){
DemoModel model = demoService.load();
Assert.assertNotNull(model);
}
}
package cn.com.glsx.dj.dataprocessing.service;
import cn.com.glsx.dj.dataprocessing.aliyun.AliyunOssFileUploadUtils;
import cn.com.glsx.dj.dataprocessing.aliyun.OssObjectUploadRequestDTO;
import cn.com.glsx.dj.dataprocessing.dto.ReplaceDTO;
import cn.com.glsx.dj.dataprocessing.mapper.PublicDataProcessingMapper;
import cn.com.glsx.dj.dataprocessing.model.PublicDataProcessing;
import cn.com.glsx.dj.dataprocessing.util.SqlFileWriterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpMethod;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* @Description todo
* @Author yelq
* @Date 2025/5/28-16:22
* @Version 1.0
*/
@Slf4j
public class PublicDataProcessingTest extends BaseServiceTest {
@Autowired
private PublicDataProcessingService publicDataProcessingService;
@Autowired
private PublicDataProcessingMapper publicDataProcessingMapper;
@Autowired
private Environment env;
@Autowired
private TaskExecutor executor;
@Autowired
private AliyunOssFileUploadUtils aliyunOssFileUploadUtils;
@Autowired
private PublicDataProcessing1Service publicDataProcessing1Service;
@Test
public void replaceFileUrl2AliyunOssUrl1Test() throws Exception {
publicDataProcessing1Service.replaceFileUrl2AliyunOssUrl("08:00,05:00");
}
@Test
public void getDataByOneConfigTest() throws Exception {
List<String> sqlList = new ArrayList<>();
PublicDataProcessing processing = new PublicDataProcessing();
processing.setTableName("reception_material_car_model_info");
processing.setColumnName("model_display_picurl");
processing.setPrimaryKeyName("id");
processing.setEndpoint("abc");
processing.setKeywordList(Arrays.asList("weapp/resource"));
List<ReplaceDTO> list = publicDataProcessingMapper.getDataByOneConfig(processing);
for (ReplaceDTO replaceDTO : list) {
String sql = String.format("UPDATE %s SET %s='%s' WHERE %s='%s';",
processing.getTableName(), processing.getColumnName(),
AliyunOssFileUploadUtils.encodeUrlFileName(replaceDTO.getOldValue()),
processing.getPrimaryKeyName(), replaceDTO.getPrimaryValue());
sqlList.add(sql);
}
String filePath = "D:\\data\\sql\\" + processing.getTableName() + "-"
+ processing.getColumnName() + System.currentTimeMillis() + ".sql";
// 写入SQL文件
SqlFileWriterUtil.writeToSqlFile(sqlList.get(0), filePath);
log.error("SQL文件写入成功");
if (sqlList.size() > 1) {
for (int i = 1; i < sqlList.size(); i++) {
// 追加内容
SqlFileWriterUtil.appendToSqlFile(sqlList.get(i), filePath);
}
}
}
@Test
public void encodeTest() throws Exception {
String link = "https://dj-oss-fastdfs-release.oss-cn-shenzhen.aliyuncs.com/weapp/resource/app-zyzs/media/common/jihu/7-1.webp?v=1";
String link1 = link.replace("http://", "").replace("https://", "");
String fileName = link1.substring(link1.lastIndexOf("/") + 1);
String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
String replaceUrl = link.replace(fileName, encodeFileName);
System.out.println(replaceUrl);
}
@Test
public void uploadFileTest() throws Exception {
String link = "https://img02.glsx.com.cn/weapp/resource/app-zyzs/media/common/jihu/7-1.webp?v=1";
// 获取rul中的文件名
String link1 = link.replace("http://", "").replace("https://", "");
String fileName = link1.substring(link1.indexOf("/") + 1);
if (!fileName.contains("/")) {
// 如果文件名不包含文件路径,为了避免文件名重复,添加一个随机数
fileName = UUID.randomUUID() + fileName;
}
// 获取文件类型
String fileType = link.substring(link.lastIndexOf(".") + 1);
// bytes 即为文件的字节流
byte[] bytes = null;
try {
bytes = new RestTemplate().execute(link, HttpMethod.GET, null, response -> {
InputStream inputStream = response.getBody();
return IOUtils.toByteArray(inputStream);
});
} catch (Exception e) {
// 处理异常,例如记录日志或抛出自定义异常
log.error("获取文件URL:{}流异常:{}", link, e.getMessage(), e);
return;
}
String aliyunUrl = aliyunOssFileUploadUtils.uploadFile(new OssObjectUploadRequestDTO(fileName,
bytes, fileType, null));
System.out.println(aliyunUrl);
}
@Test
public void executorTest() throws Exception {
System.out.println("开始=================");
for (int i = 0; i < 10; i++) {
executor.execute(() -> System.out.println(Thread.currentThread().getName()));
}
Thread.sleep(1000);
System.out.println("结束=================");
}
@Test
public void checkTimeSlotTest() throws Exception {
String timeSlotStr = env.getProperty("aliyun.oss.url.replace.time.slot");
Assert.notNull(timeSlotStr, "执行时间不能为空!");
if (PublicDataProcessingService.checkTimeSlot(timeSlotStr)) {
System.out.println("在时间范围内");
}
}
@Test
public void Test() throws Exception {
PublicDataProcessing processing = new PublicDataProcessing();
processing.setTableName("sys_order_file");
processing.setColumnName("file_path");
processing.setPrimaryKeyName("id");
processing.setEndpoint("oss-cn-shenzhen.aliyuncs.com");
processing.setKeywordList(Arrays.asList("qcimg01.glsx.com.cn", "qcwx.glsx.com.cn"));
processing.setLimitId(960);
List<ReplaceDTO> dataByOneConfig = publicDataProcessingMapper.getDataByOneConfig(processing);
System.out.println(dataByOneConfig);
}
@Test
public void replaceFileUrl2AliyunOssUrlTest() throws Exception {
String timeSlotStr = env.getProperty("aliyun.oss.url.replace.time.slot");
Assert.notNull(timeSlotStr, "执行时间不能为空!");
publicDataProcessingService.replaceFileUrl2AliyunOssUrl(timeSlotStr);
System.out.println("执行完成");
Thread.sleep(10000000);
System.out.println("执行完成---------------");
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<!-- 确保已安装mybatis generator eclipse插件 -->
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<property name="javaFileEncoding" value="UTF-8"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="org.oreframework.datasource.mybatis.mapper.OreMapper"/>
<property name="caseSensitive" value="true"/>
<property name="useActualColumnNames" value="true" />
<!--<property name="beginningDelimiter" value="`"/>-->
<!--<property name="endingDelimiter" value="`"/>-->
</plugin>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.3.227:3306/dj_smartcarlife?characterEncoding=utf8" userId="dev_admin" password="1f7e1ed2" />
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="cn.com.glsx.dj.dataprocessing.model" targetProject="../rpc-dj-dataprocessing-api/src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="META-INF/orm" targetProject="src/main/resources">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator targetPackage="cn.com.glsx.dj.dataprocessing.mapper" targetProject="MAVEN" type="XMLMAPPER">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 可配置多个 -->
<table tableName="tableName" domainObjectName="domainObjectName" enableSelectByExample="false" enableCountByExample="false" enableDeleteByExample="false" enableUpdateByExample="false">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!