Compare commits
22 Commits
a145c372b8
...
dyf-device
| Author | SHA1 | Date | |
|---|---|---|---|
| 7753444f25 | |||
| bf182ebc89 | |||
| d5a29feca3 | |||
| 0457877c09 | |||
| 1e9e815314 | |||
| b18ab98feb | |||
| 7c6f3be844 | |||
| aa69b552aa | |||
| 3dd0d4cc90 | |||
| 00a4394b43 | |||
| 2376a3b42a | |||
| 359cabbd2c | |||
| 76c11fff15 | |||
| a0ab5e9fe0 | |||
| 891ee7c1c9 | |||
| 6488b8a724 | |||
| 88b54a49f4 | |||
| dce043f63d | |||
| 759c72fc65 | |||
| 70c416779f | |||
| f4369f7581 | |||
| df28eed305 |
@ -29,10 +29,13 @@ public class AppVideoController extends BaseController {
|
||||
private final VideoProcessService videoProcessService;
|
||||
private final AudioProcessService audioProcessService;
|
||||
|
||||
/**
|
||||
* 上传视频转码code默认1:RGB565 2:BGR565
|
||||
*/
|
||||
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS,message = "请勿重复提交!")
|
||||
public R<List<String>> uploadVideo(@RequestParam("file") MultipartFile file) {
|
||||
return R.ok(videoProcessService.processVideo(file));
|
||||
public R<List<String>> uploadVideo(@RequestParam("file") MultipartFile file, @RequestParam(defaultValue = "1") int code) {
|
||||
return R.ok(videoProcessService.processVideo(file, code));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -216,6 +216,7 @@ public class AppDeviceShareService {
|
||||
uw.eq("phonenumber", bo.getPhonenumber());
|
||||
uw.set("permission", bo.getPermission());
|
||||
uw.set("update_by", userId);
|
||||
uw.set("create_by", userId);
|
||||
uw.set("update_time", new Date());
|
||||
|
||||
return appDeviceShareMapper.update(uw);
|
||||
|
||||
@ -4,6 +4,10 @@ import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceBindRecordBo;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceShareBo;
|
||||
import com.fuyuanshen.app.domain.vo.AppDeviceBindRecordVo;
|
||||
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
|
||||
import com.fuyuanshen.app.domain.vo.AppRoleVo;
|
||||
import com.fuyuanshen.app.domain.vo.AppUserVo;
|
||||
import com.fuyuanshen.common.core.constant.Constants;
|
||||
@ -33,6 +37,7 @@ import org.springframework.stereotype.Service;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 登录校验方法
|
||||
@ -52,6 +57,8 @@ public class AppLoginService {
|
||||
|
||||
private final ISysTenantService tenantService;
|
||||
private final IAppUserService appUserService;
|
||||
private final IAppDeviceShareService appDeviceShareService;
|
||||
private final IAppDeviceBindRecordService appDeviceBindRecordService;
|
||||
|
||||
|
||||
/**
|
||||
@ -188,10 +195,32 @@ public class AppLoginService {
|
||||
public void cancelAccount() {
|
||||
try {
|
||||
AppLoginUser loginUser = AppLoginHelper.getLoginUser();
|
||||
// AppLoginUser loginUser = new AppLoginUser();
|
||||
// loginUser.setUserId(1988398584423133187L);
|
||||
// loginUser.setUsername("19022528079");
|
||||
if (ObjectUtil.isNull(loginUser)) {
|
||||
return;
|
||||
}
|
||||
appUserService.deleteWithValidByIds(Collections.singletonList(loginUser.getUserId()),true);
|
||||
|
||||
AppDeviceBindRecordBo appDeviceBindRecordBo = new AppDeviceBindRecordBo();
|
||||
appDeviceBindRecordBo.setBindingUserId(loginUser.getUserId());
|
||||
List<AppDeviceBindRecordVo> appDeviceBindRecordVos = appDeviceBindRecordService.queryList(appDeviceBindRecordBo);
|
||||
if(ObjectUtil.length(appDeviceBindRecordVos)>0){
|
||||
|
||||
|
||||
// 根据设备id批量删除
|
||||
List<Long> deviceIds = appDeviceBindRecordVos.stream().map(AppDeviceBindRecordVo::getDeviceId).toList();
|
||||
appDeviceShareService.deleteByDeviceIds(deviceIds);
|
||||
|
||||
|
||||
List<Long> ids = appDeviceBindRecordVos.stream()
|
||||
.map(AppDeviceBindRecordVo::getId)
|
||||
.collect(Collectors.toList());
|
||||
appDeviceBindRecordService.deleteWithValidByIds(ids, true);
|
||||
log.info("删除绑定关系表数据:ids={}",ids);
|
||||
}
|
||||
|
||||
if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
|
||||
// 超级管理员 登出清除动态租户
|
||||
TenantHelper.clearDynamic();
|
||||
|
||||
@ -28,7 +28,7 @@ public class VideoProcessService {
|
||||
|
||||
private final VideoProcessUtil videoProcessUtil;
|
||||
|
||||
public List<String> processVideo(MultipartFile file) {
|
||||
public List<String> processVideo(MultipartFile file, int code) {
|
||||
// 1. 参数校验
|
||||
validateVideoFile(file);
|
||||
|
||||
@ -39,9 +39,10 @@ public class VideoProcessService {
|
||||
|
||||
// 3. 处理视频并提取帧数据
|
||||
List<String> hexList = videoProcessUtil.processVideoToHex(
|
||||
tempFile, FRAME_RATE, DURATION, WIDTH, HEIGHT
|
||||
tempFile, FRAME_RATE, DURATION, WIDTH, HEIGHT, code
|
||||
);
|
||||
|
||||
log.info("code: {} hexList(前100个): {}", code,
|
||||
hexList.subList(0, Math.min(100, hexList.size())));
|
||||
log.info("视频处理成功,生成Hex数据长度: {}", hexList.size());
|
||||
return hexList;
|
||||
|
||||
|
||||
@ -1,9 +1,18 @@
|
||||
package com.fuyuanshen.global.mqtt.rule.xinghan;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fuyuanshen.common.json.utils.JsonUtils;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import com.fuyuanshen.common.satoken.utils.LoginHelper;
|
||||
import com.fuyuanshen.common.sse.dto.SseMessageDto;
|
||||
import com.fuyuanshen.common.sse.utils.SseMessageUtils;
|
||||
import com.fuyuanshen.equipment.domain.Device;
|
||||
import com.fuyuanshen.equipment.domain.DeviceLog;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceMapper;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
|
||||
import com.fuyuanshen.global.mqtt.config.MqttGateway;
|
||||
@ -21,6 +30,8 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
|
||||
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
|
||||
@ -40,6 +51,18 @@ public class XinghanSendAlarmMessageRule implements MqttMessageRule {
|
||||
|
||||
private final MqttGateway mqttGateway;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private final DeviceLogMapper deviceLogMapper;
|
||||
private final DeviceMapper deviceMapper;
|
||||
/**
|
||||
* 设备上行确认消息
|
||||
*/
|
||||
public static final String BREAK_NEWS_CONFIRMATION = "I get it";
|
||||
|
||||
/**
|
||||
* 设备上行成功标记
|
||||
*/
|
||||
public static final String BREAK_NEWS_SUCCESS = "cover!";
|
||||
|
||||
@Override
|
||||
public String getCommandType() {
|
||||
@ -62,9 +85,36 @@ public class XinghanSendAlarmMessageRule implements MqttMessageRule {
|
||||
log.warn("重复消息丢弃 {}", dedupKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. I get it —— 表示用户确认收到消息
|
||||
if (BREAK_NEWS_CONFIRMATION.equalsIgnoreCase(respText)) {
|
||||
var device = deviceMapper.selectOne(new QueryWrapper<Device>().eq("device_imei", ctx.getDeviceImei()));
|
||||
// 使用MyBatis-Plus内置方法查询最新一条紧急通知
|
||||
QueryWrapper<DeviceLog> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("device_id", device.getId())
|
||||
.eq("device_action", "发送紧急通知") // 根据您的表结构调整
|
||||
.orderByDesc("create_time")
|
||||
.last("LIMIT 1");
|
||||
DeviceLog latestLog = deviceLogMapper.selectOne(queryWrapper);
|
||||
log.info("设备 {} 最新紧急通知:{}", ctx.getDeviceImei(), latestLog);
|
||||
if (latestLog == null) {
|
||||
return;
|
||||
}
|
||||
// 更新数据源字段
|
||||
UpdateWrapper<DeviceLog> updateWrapper = new UpdateWrapper<>();
|
||||
updateWrapper.eq("id", latestLog.getId()) // 条件:ID匹配
|
||||
.set("data_source", "设备已收到通知"); // 要更新的字段
|
||||
deviceLogMapper.update(null, updateWrapper);
|
||||
// 推送SSE消息
|
||||
scheduledExecutorService.schedule(() -> {
|
||||
SseMessageDto dto = new SseMessageDto();
|
||||
dto.setMessage(String.format("%s设备已收到通知!", latestLog.getDeviceName()));
|
||||
dto.setUserIds(List.of(latestLog.getCreateBy()));
|
||||
SseMessageUtils.publishMessage(dto);
|
||||
}, 5, TimeUnit.SECONDS);
|
||||
return;
|
||||
}
|
||||
// 1. cover! —— 成功标记
|
||||
if ("cover!".equalsIgnoreCase(respText)) {
|
||||
if (BREAK_NEWS_SUCCESS.equalsIgnoreCase(respText)) {
|
||||
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
|
||||
log.info("设备 {} 发送紧急通知完成", ctx.getDeviceImei());
|
||||
return;
|
||||
|
||||
@ -11,6 +11,8 @@ import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@ -37,63 +39,104 @@ public class VideoProcessUtil {
|
||||
/**
|
||||
* 处理视频并转换为Hex字符串列表
|
||||
*/
|
||||
public List<String> processVideoToHex(File videoFile, int frameRate, int duration, int width, int height) throws Exception {
|
||||
public List<String> processVideoToHex(File videoFile, int frameRate, int duration, int width, int height, int code) throws Exception {
|
||||
// 1. 提取视频帧
|
||||
List<BufferedImage> frames = extractFramesFromVideo(videoFile, frameRate, duration, width, height);
|
||||
|
||||
// 2. 转换为RGB565格式
|
||||
byte[] binaryData = convertFramesToRGB565(frames);
|
||||
if (code == 1) {
|
||||
// 1. 转换为RGB565格式
|
||||
byte[] binaryData = convertFramesToRGB565(frames);
|
||||
|
||||
// 3. 转换为Hex字符串列表
|
||||
return bytesToHexList(binaryData);
|
||||
// 2. 转换为Hex字符串列表
|
||||
return bytesToHexList(binaryData);
|
||||
} else {
|
||||
// 1. 转换为BGR565格式
|
||||
byte[] binaryData = convertFramesToBGR565(frames);
|
||||
|
||||
// 新增:直接生成 mp4
|
||||
//bgr565ToMp4(binaryData, width, height, frameRate, "output.mp4");
|
||||
|
||||
// 2. 转换为Hex字符串列表
|
||||
return bytesToHexList(binaryData);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从视频中提取帧
|
||||
*
|
||||
* @param videoFile 视频文件对象
|
||||
* @param frameRate 每秒提取的帧数(帧率)
|
||||
* @param duration 需要提取的视频时长(秒)
|
||||
* @param width 提取帧的宽度
|
||||
* @param height 提取帧的高度
|
||||
* @return 提取的帧图像列表
|
||||
* @throws Exception 如果在提取过程中发生错误
|
||||
*/
|
||||
private List<BufferedImage> extractFramesFromVideo(File videoFile, int frameRate, int duration, int width, int height) throws Exception {
|
||||
// 初始化帧列表
|
||||
List<BufferedImage> frames = new ArrayList<>();
|
||||
// 计算需要提取的总帧数 = 帧率 × 时长
|
||||
int totalFramesToExtract = frameRate * duration;
|
||||
|
||||
// 使用FFmpegFrameGrabber从视频文件中抓取帧
|
||||
try (FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(videoFile)) {
|
||||
// 启动抓取器
|
||||
grabber.start();
|
||||
|
||||
// 获取视频总帧数
|
||||
long totalFramesInVideo = grabber.getLengthInFrames();
|
||||
// 获取视频帧率,如果获取不到则默认为30fps
|
||||
int fps = (int) Math.round(grabber.getFrameRate());
|
||||
if (fps <= 0) fps = 30;
|
||||
|
||||
// 计算视频总时长(秒)
|
||||
double durationSeconds = (double) totalFramesInVideo / fps;
|
||||
// 检查视频时长是否满足要求
|
||||
if (durationSeconds < duration) {
|
||||
throw new IllegalArgumentException("视频太短,至少需要 " + duration + " 秒");
|
||||
}
|
||||
|
||||
// 计算帧间隔,用于均匀分布提取的帧
|
||||
double frameInterval = (double) totalFramesInVideo / totalFramesToExtract;
|
||||
|
||||
// 循环提取指定数量的帧
|
||||
for (int i = 0; i < totalFramesToExtract; i++) {
|
||||
// 计算目标帧号
|
||||
int targetFrameNumber = (int) Math.round(i * frameInterval);
|
||||
|
||||
// 检查目标帧号是否超出视频范围
|
||||
if (targetFrameNumber >= totalFramesInVideo) {
|
||||
throw new IllegalArgumentException("目标帧超出范围: " + targetFrameNumber);
|
||||
}
|
||||
|
||||
// 设置抓取器到目标帧
|
||||
grabber.setFrameNumber(targetFrameNumber);
|
||||
// 抓取当前帧
|
||||
Frame frame = grabber.grab();
|
||||
|
||||
// 如果成功抓取到帧且帧图像不为空
|
||||
if (frame != null && frame.image != null) {
|
||||
// 将帧转换为BufferedImage并裁剪到指定尺寸
|
||||
BufferedImage bufferedImage = Java2DFrameUtils.toBufferedImage(frame);
|
||||
frames.add(cropImage(bufferedImage, width, height));
|
||||
} else {
|
||||
// 如果无法获取帧则抛出异常
|
||||
throw new IllegalArgumentException("无法获取第 " + targetFrameNumber + "帧");
|
||||
}
|
||||
}
|
||||
|
||||
// 停止抓取器
|
||||
grabber.stop();
|
||||
}
|
||||
|
||||
// 记录提取的帧数
|
||||
log.debug("从视频中提取了 {} 帧", frames.size());
|
||||
// 返回提取的帧列表
|
||||
return frames;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将所有帧转换为 RGB565 格式字节数组
|
||||
*/
|
||||
@ -110,6 +153,55 @@ public class VideoProcessUtil {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将所有帧转换为 BGR565 格式字节数组
|
||||
*/
|
||||
private byte[] convertFramesToBGR565(List<BufferedImage> frames) throws Exception {
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
|
||||
for (BufferedImage image : frames) {
|
||||
byte[] bgr565Bytes = convertToBGR565(image);
|
||||
byteArrayOutputStream.write(bgr565Bytes);
|
||||
}
|
||||
|
||||
byte[] result = byteArrayOutputStream.toByteArray();
|
||||
log.debug("转换BGR565数据完成,总字节数: {}", result.length);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将BufferedImage转换为真正的BGR565格式字节数组
|
||||
*/
|
||||
private byte[] convertToBGR565(BufferedImage image) {
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
byte[] bgr565Data = new byte[width * height * 2];
|
||||
|
||||
int index = 0;
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
int rgb = image.getRGB(x, y);
|
||||
|
||||
// 提取RGB分量
|
||||
int red = (rgb >> 16) & 0xFF;
|
||||
int green = (rgb >> 8) & 0xFF;
|
||||
int blue = rgb & 0xFF;
|
||||
|
||||
int b = (blue >> 3) & 0x1F; // 5位蓝色
|
||||
int g = (green >> 2) & 0x3F; // 6位绿色
|
||||
int r = (red >> 3) & 0x1F; // 5位红色
|
||||
|
||||
// 正确的BGR565组合:红色在高位,蓝色在低位
|
||||
int bgr565 = (b << 11) | (g << 5) | r;
|
||||
|
||||
bgr565Data[index++] = (byte) ((bgr565 >> 8) & 0xFF);
|
||||
// 小端序存储
|
||||
bgr565Data[index++] = (byte) (bgr565 & 0xFF);
|
||||
}
|
||||
}
|
||||
return bgr565Data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为Hex字符串列表
|
||||
*/
|
||||
@ -191,4 +283,76 @@ public class VideoProcessUtil {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 BGR565 字节流直接写成 MP4(H.264)
|
||||
* @param bgr565 完整的 BGR565 裸帧流(每像素 2 字节)
|
||||
* @param width 帧宽
|
||||
* @param height 帧高
|
||||
* @param fps 帧率
|
||||
* @param outMp4 输出 mp4 文件绝对路径
|
||||
* @throws IOException 进程启动 / IO 失败
|
||||
*/
|
||||
public static void bgr565ToMp4(byte[] bgr565,
|
||||
int width,
|
||||
int height,
|
||||
int fps,
|
||||
String outMp4) throws IOException {
|
||||
|
||||
int framePixels = width * height;
|
||||
int frameBytes = framePixels * 2;
|
||||
if (bgr565.length % frameBytes != 0) {
|
||||
throw new IllegalArgumentException("字节数组长度不是整帧");
|
||||
}
|
||||
|
||||
/* 1. 构造 FFmpeg 命令 */
|
||||
String[] cmd = {
|
||||
"ffmpeg",
|
||||
"-y", // 覆盖输出
|
||||
"-f", "rawvideo",
|
||||
"-pixel_format", "bgr24",
|
||||
"-video_size", width + "x" + height,
|
||||
"-framerate", String.valueOf(fps),
|
||||
"-i", "-", // 从 stdin 读
|
||||
"-c:v", "libx264",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-crf", "23", // 画质可自己调
|
||||
outMp4
|
||||
};
|
||||
|
||||
/* 2. 启动进程 */
|
||||
ProcessBuilder pb = new ProcessBuilder(cmd);
|
||||
pb.redirectError(ProcessBuilder.Redirect.INHERIT); // 把 FFmpeg 日志打到控制台
|
||||
Process p = pb.start();
|
||||
try (OutputStream ffmpegIn = p.getOutputStream()) {
|
||||
|
||||
/* 3. 逐帧转换并写入管道 */
|
||||
byte[] bgr24 = new byte[framePixels * 3];
|
||||
for (int off = 0; off < bgr565.length; off += frameBytes) {
|
||||
for (int i = 0, j = 0; i < frameBytes; i += 2, j += 3) {
|
||||
int u = ((bgr565[off + i + 1] & 0xFF) << 8)
|
||||
| (bgr565[off + i] & 0xFF);
|
||||
int b = (u & 0x1F) << 3;
|
||||
int g = ((u >> 5) & 0x3F) << 2;
|
||||
int r = ((u >> 11) & 0x1F) << 3;
|
||||
bgr24[j] = (byte) b;
|
||||
bgr24[j + 1] = (byte) g;
|
||||
bgr24[j + 2] = (byte) r;
|
||||
}
|
||||
ffmpegIn.write(bgr24);
|
||||
}
|
||||
ffmpegIn.flush();
|
||||
}
|
||||
|
||||
/* 4. 等待编码结束 */
|
||||
try {
|
||||
int exit = p.waitFor();
|
||||
if (exit != 0) {
|
||||
throw new IOException("FFmpeg 异常退出,code=" + exit);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("等待 FFmpeg 被中断", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -269,4 +269,4 @@ justauth:
|
||||
server-url: https://demo.gitea.com
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitea
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitea
|
||||
@ -3,18 +3,43 @@ package com.fuyuanshen.common.core.utils.file;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageWriteParam;
|
||||
import javax.imageio.ImageWriter;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* 图片压缩工具类
|
||||
*
|
||||
* @author AprilWind
|
||||
*/
|
||||
@Slf4j
|
||||
public class ImageCompressUtil {
|
||||
|
||||
/**
|
||||
* 默认压缩目标大小(100KB)
|
||||
*/
|
||||
private static final int DEFAULT_COMPRESS_SIZE = 100 * 1024;
|
||||
|
||||
/**
|
||||
* 默认触发压缩的大小(1MB)
|
||||
*/
|
||||
private static final int DEFAULT_TRIGGER_SIZE = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 压缩图片到指定大小以下(默认100KB)
|
||||
*
|
||||
* @param imageData 原始图片数据
|
||||
* @return 压缩后的图片数据
|
||||
*/
|
||||
public static byte[] compressImage(byte[] imageData) {
|
||||
return compressImage(imageData, DEFAULT_COMPRESS_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩图片到指定大小以下
|
||||
*
|
||||
@ -36,24 +61,54 @@ public class ImageCompressUtil {
|
||||
return imageData;
|
||||
}
|
||||
|
||||
// 计算压缩比例
|
||||
double scale = Math.sqrt((double) maxSize / imageData.length);
|
||||
// 确保至少压缩到一半大小,避免压缩效果不明显
|
||||
scale = Math.max(scale, 0.5);
|
||||
// 检查图片是否包含透明度
|
||||
boolean hasAlpha = hasAlpha(originalImage);
|
||||
String formatName = hasAlpha ? "png" : "jpg";
|
||||
|
||||
// 压缩图片
|
||||
byte[] compressedData = compressImageByScale(originalImage, scale);
|
||||
// 对于小尺寸PNG图片可跳过压缩以保持图像质量
|
||||
if ("png".equals(formatName) && imageData.length <= 2 * maxSize) {
|
||||
log.debug("PNG图片大小适中({} bytes),跳过压缩", imageData.length);
|
||||
return imageData;
|
||||
}
|
||||
|
||||
// 先尝试质量压缩
|
||||
byte[] compressedData = compressImageQuality(originalImage, formatName, 0.8f);
|
||||
|
||||
// 如果质量压缩后仍大于目标大小,则进行尺寸压缩
|
||||
if (compressedData.length > maxSize) {
|
||||
// 计算缩放比例
|
||||
double scale = Math.sqrt((double) maxSize / compressedData.length);
|
||||
scale = Math.max(scale, 0.5); // 最小缩放到原来的一半
|
||||
|
||||
// 尺寸压缩
|
||||
compressedData = compressImageByScale(originalImage, scale, formatName);
|
||||
}
|
||||
|
||||
// 如果压缩后还是太大,继续压缩
|
||||
int attempts = 0;
|
||||
while (compressedData.length > maxSize && attempts < 5) {
|
||||
scale *= 0.8; // 每次缩小20%
|
||||
compressedData = compressImageByScale(originalImage, scale);
|
||||
// 优先降低质量
|
||||
float quality = Math.max(0.1f, 0.8f - attempts * 0.1f);
|
||||
compressedData = compressImageQuality(originalImage, formatName, quality);
|
||||
|
||||
// 如果质量压缩不够,再缩小尺寸
|
||||
if (compressedData.length > maxSize) {
|
||||
double scale = 0.9 - attempts * 0.1; // 逐步缩小尺寸
|
||||
scale = Math.max(scale, 0.5);
|
||||
compressedData = compressImageByScale(originalImage, scale, formatName);
|
||||
}
|
||||
attempts++;
|
||||
}
|
||||
|
||||
log.info("图片压缩完成,原始大小: {} bytes, 压缩后大小: {} bytes, 压缩比例: {}",
|
||||
imageData.length, compressedData.length, String.format("%.2f", scale));
|
||||
log.info("图片压缩完成,原始大小: {} bytes, 压缩后大小: {} bytes, 压缩率: {}%",
|
||||
imageData.length, compressedData.length,
|
||||
String.format("%.2f", (1.0 - (double) compressedData.length / imageData.length) * 100));
|
||||
|
||||
// 如果压缩后反而变大了,则使用原始数据
|
||||
if (compressedData.length >= imageData.length) {
|
||||
log.debug("压缩后数据变大,使用原始数据");
|
||||
return imageData;
|
||||
}
|
||||
|
||||
return compressedData;
|
||||
} catch (Exception e) {
|
||||
@ -62,16 +117,16 @@ public class ImageCompressUtil {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 按比例缩放图片
|
||||
*
|
||||
* @param originalImage 原始图片
|
||||
* @param scale 缩放比例
|
||||
* @param formatName 图片格式
|
||||
* @return 缩放后的图片数据
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
private static byte[] compressImageByScale(BufferedImage originalImage, double scale) throws IOException {
|
||||
private static byte[] compressImageByScale(BufferedImage originalImage, double scale, String formatName) throws IOException {
|
||||
int width = (int) (originalImage.getWidth() * scale);
|
||||
int height = (int) (originalImage.getHeight() * scale);
|
||||
|
||||
@ -79,13 +134,73 @@ public class ImageCompressUtil {
|
||||
Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = bufferedImage.createGraphics();
|
||||
|
||||
// 绘制缩放后的图片
|
||||
g2d.drawImage(scaledImage, 0, 0, null);
|
||||
g2d.dispose();
|
||||
|
||||
// 输出为JPEG格式
|
||||
// 输出为指定格式
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(bufferedImage, "jpg", baos);
|
||||
ImageIO.write(bufferedImage, formatName, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* 按质量压缩图片
|
||||
*
|
||||
* @param originalImage 原始图片
|
||||
* @param formatName 图片格式
|
||||
* @param quality 压缩质量(0.1-1.0)
|
||||
* @return 压缩后的图片数据
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
private static byte[] compressImageQuality(BufferedImage originalImage, String formatName, float quality) throws IOException {
|
||||
// 创建压缩参数
|
||||
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
|
||||
if (!writers.hasNext()) {
|
||||
log.warn("找不到合适的图片写入器");
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(originalImage, formatName, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
ImageWriter writer = writers.next();
|
||||
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||
|
||||
// 设置压缩参数
|
||||
if (param.canWriteCompressed()) {
|
||||
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||
param.setCompressionQuality(quality);
|
||||
}
|
||||
|
||||
// 写入压缩后的图片数据
|
||||
ByteArrayOutputStream compressedOutputStream = new ByteArrayOutputStream();
|
||||
writer.setOutput(ImageIO.createImageOutputStream(compressedOutputStream));
|
||||
writer.write(null, new javax.imageio.IIOImage(originalImage, null, null), param);
|
||||
writer.dispose();
|
||||
|
||||
return compressedOutputStream.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查图片是否包含透明度
|
||||
*
|
||||
* @param image 图片
|
||||
* @return 是否包含透明度
|
||||
*/
|
||||
private static boolean hasAlpha(BufferedImage image) {
|
||||
return image.getType() == BufferedImage.TYPE_4BYTE_ABGR ||
|
||||
image.getType() == BufferedImage.TYPE_INT_ARGB ||
|
||||
image.getColorModel().hasAlpha();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断图片是否需要压缩(超过1MB)
|
||||
*
|
||||
* @param imageData 图片数据
|
||||
* @return 是否需要压缩
|
||||
*/
|
||||
public static boolean needCompress(byte[] imageData) {
|
||||
return imageData.length > DEFAULT_TRIGGER_SIZE;
|
||||
}
|
||||
}
|
||||
@ -9,6 +9,8 @@ import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
|
||||
import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 设备分享Mapper接口
|
||||
*
|
||||
@ -27,4 +29,6 @@ public interface AppDeviceShareMapper extends BaseMapperPlus<AppDeviceShare, App
|
||||
* @return 设备分享
|
||||
*/
|
||||
Page<AppDeviceShareVo> selectWebDeviceShareList(@Param("bo") AppDeviceShareBo bo, Page<AppDeviceShareVo> page);
|
||||
|
||||
void deleteByDeviceIds(@Param("deviceIds") List<Long> deviceIds);
|
||||
}
|
||||
|
||||
@ -67,4 +67,6 @@ public interface IAppDeviceShareService {
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
|
||||
TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery);
|
||||
|
||||
void deleteByDeviceIds(List<Long> deviceIds);
|
||||
}
|
||||
|
||||
@ -166,4 +166,9 @@ public class AppDeviceShareServiceImpl implements IAppDeviceShareService {
|
||||
});
|
||||
return TableDataInfo.build(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteByDeviceIds(List<Long> deviceIds) {
|
||||
baseMapper.deleteByDeviceIds(deviceIds);
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,6 +3,12 @@
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.fuyuanshen.app.mapper.AppDeviceShareMapper">
|
||||
<delete id="deleteByDeviceIds">
|
||||
delete from app_device_share where device_id in
|
||||
<foreach item="item" collection="deviceIds" separator="," open="(" close=")">
|
||||
#{item}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
<select id="otherDeviceShareList" resultType="com.fuyuanshen.app.domain.vo.AppDeviceShareVo">
|
||||
select d.device_name,
|
||||
|
||||
@ -3,9 +3,7 @@ package com.fuyuanshen.equipment.controller;
|
||||
|
||||
import com.alibaba.excel.EasyExcel;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fuyuanshen.common.core.constant.ResponseMessageConstants;
|
||||
import com.fuyuanshen.common.core.domain.R;
|
||||
import com.fuyuanshen.common.core.domain.ResponseVO;
|
||||
import com.fuyuanshen.common.core.domain.model.LoginUser;
|
||||
import com.fuyuanshen.common.core.utils.file.FileUtil;
|
||||
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
|
||||
@ -18,7 +16,6 @@ import com.fuyuanshen.equipment.domain.dto.DeviceExcelImportDTO;
|
||||
import com.fuyuanshen.equipment.domain.dto.ImportResult;
|
||||
import com.fuyuanshen.equipment.domain.form.DeviceForm;
|
||||
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
|
||||
import com.fuyuanshen.equipment.domain.vo.CustomerVo;
|
||||
import com.fuyuanshen.equipment.excel.DeviceImportParams;
|
||||
import com.fuyuanshen.equipment.excel.HeadValidateListener;
|
||||
import com.fuyuanshen.equipment.excel.UploadDeviceDataListener;
|
||||
|
||||
@ -4,6 +4,8 @@ import com.alibaba.excel.converters.Converter;
|
||||
import com.alibaba.excel.metadata.GlobalConfiguration;
|
||||
import com.alibaba.excel.metadata.data.WriteCellData;
|
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty;
|
||||
import com.fuyuanshen.common.core.utils.file.ImageCompressUtil;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -12,19 +14,40 @@ import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.Base64;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-06-0618:56
|
||||
*/
|
||||
|
||||
public class IgnoreFailedImageConverter implements Converter<URL> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(IgnoreFailedImageConverter.class);
|
||||
|
||||
|
||||
// 重试次数
|
||||
private static final int MAX_RETRIES = 3;
|
||||
// 指数退避初始延迟(毫秒)
|
||||
private static final int INITIAL_DELAY = 1000;
|
||||
// 图片压缩阈值(1MB)
|
||||
private static final int COMPRESSION_THRESHOLD = 1024 * 1024;
|
||||
// 压缩目标大小(100KB)
|
||||
private static final int COMPRESSION_TARGET = 100 * 1024;
|
||||
// 用于跟踪本次任务中使用到的URL缓存键
|
||||
private static final ThreadLocal<Set<String>> USED_CACHE_KEYS = new ThreadLocal<Set<String>>() {
|
||||
@Override
|
||||
protected Set<String> initialValue() {
|
||||
return new HashSet<>();
|
||||
}
|
||||
};
|
||||
|
||||
// 创建线程池用于并发处理图片
|
||||
private static final ExecutorService IMAGE_PROCESSING_EXECUTOR = Executors.newFixedThreadPool(
|
||||
Runtime.getRuntime().availableProcessors() * 2);
|
||||
|
||||
@Override
|
||||
public Class<?> supportJavaTypeKey() {
|
||||
@ -34,22 +57,64 @@ public class IgnoreFailedImageConverter implements Converter<URL> {
|
||||
@Override
|
||||
public WriteCellData<?> convertToExcelData(URL value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
|
||||
if (value == null) {
|
||||
logger.debug("图片URL为空");
|
||||
logger.info("图片URL为空");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
try {
|
||||
// 使用CompletableFuture异步处理图片加载
|
||||
CompletableFuture<WriteCellData<?>> future = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return loadImageData(value);
|
||||
} catch (Exception e) {
|
||||
logger.error("异步加载图片失败: {}", value, e);
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}, IMAGE_PROCESSING_EXECUTOR);
|
||||
|
||||
// 设置超时时间,防止长时间阻塞
|
||||
return future.get(30, TimeUnit.SECONDS);
|
||||
} catch (Exception e) {
|
||||
logger.error("图片处理异常: {}", value, e);
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载图片数据的核心方法
|
||||
* @param value 图片URL
|
||||
* @return WriteCellData对象
|
||||
*/
|
||||
private WriteCellData<?> loadImageData(URL value) {
|
||||
String cacheKey = "excel:image:" + value.toString();
|
||||
|
||||
// 将当前使用的缓存键添加到集合中
|
||||
USED_CACHE_KEYS.get().add(cacheKey);
|
||||
|
||||
// 尝试从缓存获取
|
||||
String cachedData = RedisUtils.getCacheObject(cacheKey);
|
||||
if (cachedData != null) {
|
||||
// 从缓存中读取Base64编码的数据并解码
|
||||
byte[] cachedBytes = Base64.getDecoder().decode(cachedData);
|
||||
logger.info("从缓存获取图片数据: {}, 大小: {} 字节", value, cachedBytes.length);
|
||||
return new WriteCellData<>(cachedBytes);
|
||||
}
|
||||
|
||||
// 缓存未命中,从URL加载
|
||||
// 尝试多次加载图片
|
||||
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
logger.debug("开始加载图片: {}, 尝试次数: {}", value, attempt);
|
||||
logger.info("开始加载图片: {}, 尝试次数: {}", value, attempt);
|
||||
URLConnection conn = value.openConnection();
|
||||
// 增加连接和读取超时时间
|
||||
conn.setConnectTimeout(10000); // 10秒连接超时
|
||||
conn.setReadTimeout(30000); // 30秒读取超时
|
||||
|
||||
conn.setConnectTimeout(5000); // 5秒连接超时
|
||||
conn.setReadTimeout(15000); // 15秒读取超时
|
||||
|
||||
// 添加User-Agent避免被服务器拦截
|
||||
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 ExcelExporter/1.0");
|
||||
|
||||
// 添加Connection: close避免保持连接
|
||||
conn.setRequestProperty("Connection", "close");
|
||||
|
||||
// 如果是HTTP连接,设置一些额外的属性
|
||||
if (conn instanceof HttpURLConnection) {
|
||||
HttpURLConnection httpConn = (HttpURLConnection) conn;
|
||||
@ -58,38 +123,44 @@ public class IgnoreFailedImageConverter implements Converter<URL> {
|
||||
httpConn.setUseCaches(false);
|
||||
// 跟随重定向
|
||||
httpConn.setInstanceFollowRedirects(true);
|
||||
|
||||
|
||||
// 检查响应码
|
||||
int responseCode = httpConn.getResponseCode();
|
||||
if (responseCode != HttpURLConnection.HTTP_OK) {
|
||||
logger.warn("HTTP响应码异常: {}, URL: {}", responseCode, value);
|
||||
logger.info("HTTP响应码异常: {}, URL: {}", responseCode, value);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
// 等待后重试
|
||||
waitForRetry(attempt);
|
||||
continue;
|
||||
} else {
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
long contentLength = conn.getContentLengthLong();
|
||||
logger.debug("连接建立成功,图片大小: {} 字节", contentLength);
|
||||
|
||||
logger.info("连接建立成功,图片大小: {} 字节", contentLength);
|
||||
|
||||
// 检查内容长度是否有效
|
||||
if (contentLength == 0) {
|
||||
logger.warn("图片文件为空: {}", value);
|
||||
logger.info("图片文件为空: {}", value);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
waitForRetry(attempt);
|
||||
continue;
|
||||
} else {
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 限制图片大小(防止过大文件导致内存问题)
|
||||
if (contentLength > 10 * 1024 * 1024) { // 10MB限制
|
||||
logger.warn("图片文件过大 ({} bytes),跳过加载: {}", contentLength, value);
|
||||
logger.info("图片文件过大 ({} bytes),跳过加载: {}", contentLength, value);
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
@ -97,46 +168,99 @@ public class IgnoreFailedImageConverter implements Converter<URL> {
|
||||
// byte[] bytes = FileUtils.readInputStream(inputStream, value.toString());
|
||||
// 替代 FileUtils.readInputStream 的自定义方法
|
||||
byte[] bytes = readInputStream(inputStream);
|
||||
|
||||
|
||||
// 检查读取到的数据是否为空
|
||||
if (bytes == null || bytes.length == 0) {
|
||||
logger.warn("读取到空的图片数据: {}", value);
|
||||
logger.info("读取到空的图片数据: {}", value);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
waitForRetry(attempt);
|
||||
continue;
|
||||
} else {
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("成功读取图片数据,大小: {} 字节", bytes.length);
|
||||
|
||||
// 如果图片大于1MB,则进行压缩
|
||||
if (bytes.length > COMPRESSION_THRESHOLD) {
|
||||
logger.info("图片大小超过1MB ({} bytes),开始压缩", bytes.length);
|
||||
long beforeCompressSize = bytes.length;
|
||||
|
||||
// 先尝试质量压缩
|
||||
byte[] compressed = ImageCompressUtil.compressImage(bytes, COMPRESSION_TARGET);
|
||||
|
||||
// 如果压缩后变大了,使用原始数据
|
||||
if (compressed.length >= bytes.length) {
|
||||
compressed = bytes;
|
||||
}
|
||||
|
||||
bytes = compressed;
|
||||
long afterCompressSize = bytes.length;
|
||||
logger.info("图片压缩完成,压缩前大小: {} bytes, 压缩后大小: {} bytes, 压缩率: {}",
|
||||
beforeCompressSize, afterCompressSize,
|
||||
String.format("%.2f", (1.0 - (double) afterCompressSize / beforeCompressSize) * 100));
|
||||
}
|
||||
|
||||
logger.info("成功读取图片数据,大小: {} 字节", bytes.length);
|
||||
// 将数据写入缓存,不设置过期时间,使用Base64编码存储
|
||||
String encodedData = Base64.getEncoder().encodeToString(bytes);
|
||||
RedisUtils.setCacheObject(cacheKey, encodedData);
|
||||
return new WriteCellData<>(bytes);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("图片加载失败: {}, 尝试次数: {}, 原因: {}", value, attempt, e.getMessage(), e);
|
||||
logger.info("图片加载失败: {}, 尝试次数: {}, 原因: {}", value, attempt, e.getMessage(), e);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
// 等待后重试
|
||||
waitForRetry(attempt);
|
||||
} else {
|
||||
// 最后一次尝试也失败了
|
||||
logger.error("图片加载最终失败,已重试 {} 次: {}", MAX_RETRIES, value, e);
|
||||
logger.info("图片加载最终失败,已重试 {} 次: {}", MAX_RETRIES, value, e);
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]); // 返回空数组而不是 null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 所有尝试都失败了
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理未使用的缓存
|
||||
* 任务结束后调用此方法,删除本次任务中未使用的URL缓存
|
||||
*/
|
||||
public static void cleanUnusedCache() {
|
||||
Set<String> usedKeys = USED_CACHE_KEYS.get();
|
||||
if (usedKeys != null && !usedKeys.isEmpty()) {
|
||||
// 获取所有图片缓存键
|
||||
Iterable<String> allKeys = RedisUtils.keys("excel:image:*");
|
||||
if (allKeys != null) {
|
||||
// 删除未使用的缓存
|
||||
for (String key : allKeys) {
|
||||
if (!usedKeys.contains(key)) {
|
||||
RedisUtils.deleteObject(key);
|
||||
logger.info("删除未使用的缓存: {}", key);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 清理ThreadLocal
|
||||
USED_CACHE_KEYS.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待重试,使用指数退避策略
|
||||
*
|
||||
* @param attempt 当前尝试次数
|
||||
*/
|
||||
private void waitForRetry(int attempt) {
|
||||
try {
|
||||
long delay = (long) INITIAL_DELAY * (1L << (attempt - 1)); // 指数退避
|
||||
logger.debug("等待 {} 毫秒后重试...", delay);
|
||||
logger.info("等待 {} 毫秒后重试...", delay);
|
||||
Thread.sleep(delay);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
@ -159,14 +283,48 @@ public class IgnoreFailedImageConverter implements Converter<URL> {
|
||||
while ((bytesRead = inputStream.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, bytesRead);
|
||||
totalBytes += bytesRead;
|
||||
|
||||
|
||||
// 如果读取的数据过大,提前终止
|
||||
if (totalBytes > 10 * 1024 * 1024) { // 10MB限制
|
||||
logger.warn("读取的图片数据超过10MB限制,提前终止");
|
||||
logger.info("读取的图片数据超过10MB限制,提前终止");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预加载图片到缓存
|
||||
* @param imageUrls 图片URL列表
|
||||
*/
|
||||
public static void preloadImages(Set<URL> imageUrls) {
|
||||
if (imageUrls == null || imageUrls.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("开始预加载 {} 张图片", imageUrls.size());
|
||||
|
||||
// 使用并行流并发预加载图片
|
||||
imageUrls.parallelStream().forEach(url -> {
|
||||
try {
|
||||
String cacheKey = "excel:image:" + url.toString();
|
||||
// 如果缓存中没有,则异步加载
|
||||
if (!RedisUtils.hasKey(cacheKey)) {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
// 简化版图片加载逻辑,只加载到缓存
|
||||
new IgnoreFailedImageConverter().loadImageData(url);
|
||||
} catch (Exception e) {
|
||||
logger.warn("预加载图片失败: {}", url, e);
|
||||
}
|
||||
}, IMAGE_PROCESSING_EXECUTOR);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("预加载图片异常: {}", url, e);
|
||||
}
|
||||
});
|
||||
|
||||
logger.info("图片预加载任务已提交");
|
||||
}
|
||||
}
|
||||
|
||||
@ -13,7 +13,7 @@ import java.net.URL;
|
||||
* 设备及完整类型信息导出DTO
|
||||
*
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-11-0416:25
|
||||
* @date: 2025-11-04 16:25
|
||||
*/
|
||||
@Data
|
||||
@HeadRowHeight(20) // 表头行高
|
||||
|
||||
@ -137,4 +137,13 @@ public interface DeviceMapper extends BaseMapper<Device> {
|
||||
List<DeviceUsageFrequencyVo> getDeviceUsageFrequency(@Param("days") int days);
|
||||
|
||||
List<OnlineStatusVo> queryOnlineStatusList();
|
||||
|
||||
/**
|
||||
* 根据设备类型ID查询设备数量
|
||||
*
|
||||
* @param deviceTypeId 设备类型ID
|
||||
* @return 设备数量
|
||||
*/
|
||||
int countByDeviceTypeId(@Param("deviceTypeId") Long deviceTypeId);
|
||||
|
||||
}
|
||||
@ -83,6 +83,7 @@ public class DeviceExportService {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 导出设备数据(包含完整设备类型信息)
|
||||
*
|
||||
@ -183,6 +184,7 @@ public class DeviceExportService {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 转换定位方式代码为中文描述
|
||||
*
|
||||
|
||||
@ -19,11 +19,8 @@ import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
|
||||
import com.fuyuanshen.common.satoken.utils.LoginHelper;
|
||||
import com.fuyuanshen.customer.domain.Customer;
|
||||
import com.fuyuanshen.customer.mapper.CustomerMapper;
|
||||
import com.fuyuanshen.equipment.constants.DeviceConstants;
|
||||
import com.fuyuanshen.equipment.domain.*;
|
||||
import com.fuyuanshen.equipment.domain.bo.DeviceFenceAccessRecordBo;
|
||||
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
|
||||
import com.fuyuanshen.equipment.domain.dto.FenceCheckResponse;
|
||||
import com.fuyuanshen.equipment.domain.form.DeviceForm;
|
||||
import com.fuyuanshen.equipment.domain.query.DeviceAssignmentQuery;
|
||||
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
|
||||
@ -33,7 +30,10 @@ import com.fuyuanshen.equipment.enums.BindingStatusEnum;
|
||||
import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
|
||||
import com.fuyuanshen.equipment.enums.DeviceActiveStatusEnum;
|
||||
import com.fuyuanshen.equipment.mapper.*;
|
||||
import com.fuyuanshen.equipment.service.*;
|
||||
import com.fuyuanshen.equipment.service.DeviceAssignmentsService;
|
||||
import com.fuyuanshen.equipment.service.DeviceService;
|
||||
import com.fuyuanshen.equipment.service.DeviceTypeGrantsService;
|
||||
import com.fuyuanshen.equipment.service.IDeviceGeoFenceService;
|
||||
import com.fuyuanshen.equipment.utils.FileHashUtil;
|
||||
import com.fuyuanshen.system.domain.vo.SysOssVo;
|
||||
import com.fuyuanshen.system.domain.vo.SysRoleVo;
|
||||
@ -41,15 +41,11 @@ import com.fuyuanshen.system.service.ISysOssService;
|
||||
import com.fuyuanshen.system.service.ISysRoleService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
@ -192,10 +188,21 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
throw new BadRequestException("设备IMEI已存在!!!");
|
||||
}
|
||||
|
||||
DeviceTypeGrants typeGrants = new DeviceTypeGrants();
|
||||
|
||||
if (deviceForm.getDeviceType() != null) {
|
||||
DeviceTypeQueryCriteria queryCriteria = new DeviceTypeQueryCriteria();
|
||||
queryCriteria.setDeviceTypeId(deviceForm.getDeviceType());
|
||||
typeGrants = deviceTypeGrantsMapper.selectById(queryCriteria.getDeviceTypeId());
|
||||
if (typeGrants == null) {
|
||||
throw new Exception("设备类型不存在!!!");
|
||||
}
|
||||
}
|
||||
|
||||
// 检查设备类型是否存在,如果不存在则创建
|
||||
DeviceType deviceType = null;
|
||||
if (deviceForm.getDeviceType() != null) {
|
||||
deviceType = deviceTypeMapper.selectById(deviceForm.getDeviceType());
|
||||
deviceType = deviceTypeMapper.selectById(typeGrants.getDeviceTypeId());
|
||||
} else if (deviceForm.getTypeName() != null) {
|
||||
deviceType = deviceTypeMapper.selectOne(new QueryWrapper<DeviceType>().eq("type_name", deviceForm.getTypeName()));
|
||||
}
|
||||
@ -278,7 +285,11 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
// 保存图片并获取URL
|
||||
if (deviceForm.getFile() != null) {
|
||||
String fileHash = fileHashUtil.hash(deviceForm.getFile());
|
||||
SysOssVo upload = ossService.updateHash(deviceForm.getFile(),fileHash);
|
||||
SysOssVo upload = ossService.updateHash(deviceForm.getFile(), fileHash);
|
||||
// 强制将HTTP替换为HTTPS
|
||||
if (upload.getUrl() != null && upload.getUrl().startsWith("http://")) {
|
||||
upload.setUrl(upload.getUrl().replaceFirst("^http://", "https://"));
|
||||
}
|
||||
// 设置图片路径
|
||||
deviceForm.setDevicePic(upload.getUrl());
|
||||
}
|
||||
@ -353,7 +364,7 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
// 处理上传的图片
|
||||
if (deviceForm.getFile() != null) {
|
||||
String fileHash = fileHashUtil.hash(deviceForm.getFile());
|
||||
SysOssVo oss = ossService.updateHash(deviceForm.getFile(),fileHash);
|
||||
SysOssVo oss = ossService.updateHash(deviceForm.getFile(), fileHash);
|
||||
// 强制将HTTP替换为HTTPS
|
||||
if (oss.getUrl() != null && oss.getUrl().startsWith("http://")) {
|
||||
oss.setUrl(oss.getUrl().replaceFirst("^http://", "https://"));
|
||||
|
||||
@ -224,6 +224,16 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
|
||||
throw new RuntimeException("设备类型不存在");
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (!deviceType.getTypeName().equals(resources.getTypeName())) {
|
||||
int count = deviceMapper.countByDeviceTypeId(deviceType.getId());
|
||||
if (count > 0) {
|
||||
throw new RuntimeException("该设备类型下已有绑定设备,无法修改设备类型名称!!!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// List<Device> devices = deviceMapper.selectList(new QueryWrapper<Device>()
|
||||
// .eq("device_type", deviceTypeGrants.getDeviceTypeId()));
|
||||
// if (CollectionUtil.isNotEmpty(devices)) {
|
||||
|
||||
@ -497,4 +497,11 @@
|
||||
FROM device a left join device_type b on a.device_type = b.id where b.communication_mode in (0, 2) and a.online_status in (1,2)
|
||||
</select>
|
||||
|
||||
<!-- 根据设备类型ID查询设备数量 -->
|
||||
<select id="countByDeviceTypeId" resultType="int">
|
||||
SELECT COUNT(*)
|
||||
FROM device
|
||||
WHERE device_type = #{deviceTypeId}
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@ -51,6 +51,7 @@ public class SysOss extends TenantEntity {
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
/**
|
||||
* 内容哈希
|
||||
*/
|
||||
|
||||
@ -6,6 +6,7 @@ import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fuyuanshen.common.core.utils.file.ImageCompressUtil;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import com.fuyuanshen.common.core.constant.CacheNames;
|
||||
@ -143,7 +144,7 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getFileSuffix()), SysOss::getFileSuffix, bo.getFileSuffix());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getUrl()), SysOss::getUrl, bo.getUrl());
|
||||
lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
|
||||
SysOss::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
|
||||
SysOss::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
|
||||
lqw.eq(ObjectUtil.isNotNull(bo.getCreateBy()), SysOss::getCreateBy, bo.getCreateBy());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getService()), SysOss::getService, bo.getService());
|
||||
lqw.orderByAsc(SysOss::getOssId);
|
||||
@ -169,7 +170,7 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
|
||||
|
||||
@Override
|
||||
public int updateHashById(long ossId, String fileHash) {
|
||||
return baseMapper.updateHashById(ossId,fileHash);
|
||||
return baseMapper.updateHashById(ossId, fileHash);
|
||||
}
|
||||
|
||||
|
||||
@ -191,6 +192,7 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
|
||||
storage.download(sysOss.getFileName(), response.getOutputStream(), response::setContentLengthLong);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传 MultipartFile 到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
@ -209,14 +211,22 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
|
||||
OssClient storage = OssFactory.instance();
|
||||
UploadResult uploadResult;
|
||||
try {
|
||||
uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
|
||||
byte[] imageData = file.getBytes();
|
||||
// 检查是否需要压缩
|
||||
if (ImageCompressUtil.needCompress(imageData)) {
|
||||
// 压缩到100KB以内
|
||||
imageData = ImageCompressUtil.compressImage(imageData);
|
||||
// 使用压缩后的数据
|
||||
}
|
||||
uploadResult = storage.uploadSuffix(imageData, suffix, file.getContentType());
|
||||
} catch (IOException e) {
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
// 保存文件信息
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult,hash);
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult, hash);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传 MultipartFile 到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
@ -236,7 +246,7 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
// 保存文件信息
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult,null);
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult, null);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -252,11 +262,10 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
|
||||
OssClient storage = OssFactory.instance();
|
||||
UploadResult uploadResult = storage.uploadSuffix(file, suffix);
|
||||
// 保存文件信息
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult,null);
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult, null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 上传二进制数据到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
@ -281,7 +290,7 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
|
||||
uploadResult = storage.uploadSuffix(data, suffix, "image/jpeg"); // 假设是图片类型,可以根据实际需要修改
|
||||
|
||||
// 保存文件信息
|
||||
return buildResultEntity(fileName, suffix, storage.getConfigKey(), uploadResult,null);
|
||||
return buildResultEntity(fileName, suffix, storage.getConfigKey(), uploadResult, null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user