断点续传+测试方法完整示例

因为看不懂网上的断点续传案例,而且又不能直接复制使用,干脆自己想想写了一个。

上传入参类:

java 复制代码
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * 断点续传接收实体类
 *
 * @author kwy
 * @date 2024/11/18
 */
@Data
@ApiModel("镜像文件断点续传接收实体类")
public class ImageFileBreakpointResumeDTO {

    @ApiModelProperty(value = "上传的文件流")
    @NotNull(message = "上传的文件流不能为空")
    @JsonIgnore
    private MultipartFile multipartFile;

    @ApiModelProperty(value = "云命名空间")
    @NotBlank(message = "云命名空间不能为空")
    private String namespace;

    @ApiModelProperty(value = "镜像名称")
    @NotBlank(message = "镜像名称不能为空")
    private String name;

    @ApiModelProperty(value = "版本号")
    @NotBlank(message = "版本号不能为空")
    private String version;

    @ApiModelProperty(value = "文件上传标识")
    @NotBlank(message = "文件上传标识不能为空")
    private String taskId;

    @ApiModelProperty(value = "分片总数")
    @NotNull(message = "分片总数不能为空")
    private Integer numTotal;

    @ApiModelProperty(value = "上传到第几片")
    @NotNull(message = "上传到第几片不能为空")
    private Integer uploadNum;

    @ApiModelProperty(value = "文件名称")
    @NotBlank(message = "文件名称不能为空")
    private String fileName;

    @ApiModelProperty(value = "是否上传成功", hidden = true)
    private Boolean status;

    @ApiModelProperty(value = "分片文件路径", hidden = true)
    private String filePath;
}

controller层:

java 复制代码
  @PostMapping("/breakpointResumeFile")
    @ApiOperation(value = "断点续传|重试上传镜像文件")
    public ResponseData<String> breakpointResumeFile(@Validated ImageFileBreakpointResumeDTO dto) {
        return ResponseData.ok(disImageMgrService.breakpointResumeFile(dto));
    }

    @PostMapping("/test")
    @ApiOperation(value = "断点续传|重试上传镜像文件 - 测试")
    public ResponseData<Boolean> test() {
        disImageMgrService.test();
        return ResponseData.ok();
    }

    /**
     * 为避免本地临时文件过多,清除临时分片文件
     * ps:请勿在用户上传的期间操作
     */
    @ApiOperation(value = "清除临时分片文件")
    @PostMapping("/clearItemFile")
    public ResponseData<Boolean> clearItemFile() {
        disImageMgrService.clearItemFile();
        return ResponseData.ok();
    }

service层:

接口

java 复制代码
   /**
     * 上传镜像文件
     *
     * @param dto 文件参数内容
     * @return 合并时返回dockerFile值,否则返回null
     */
    String breakpointResumeFile(ImageFileBreakpointResumeDTO dto);

    /**
     * 测试断点续传
     */
    void test();

    /**
     * 为避免本地临时文件过多,清除临时分片文件
     * ps:请勿在用户上传的期间操作
     */
    void clearItemFile();

实现方法

java 复制代码
    @Override
    public String breakpointResumeFile(ImageFileBreakpointResumeDTO dto) {
        MultipartFile multipartFile = dto.getMultipartFile();
        // 校验
        if (multipartFile.getSize() <= 0) {
            throw new CommonException("无效文件");
        }

        String taskName = "IMAGE_BREAKPOINT_RESUME_TASK_ID_" + dto.getTaskId();
        StringBuilder path = new StringBuilder("/imageBreakpointResumeStorage/");
        path.append(dto.getNamespace()).append("/").append(dto.getName()).append("/").append(dto.getVersion()).append("/").append(dto.getTaskId());
        File directory = new File(path.toString());
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 本次切片文件
        String filePath = path + "/" + multipartFile.getOriginalFilename();
        dto.setFilePath(filePath);

        Map<String, String> allRecordMap = new HashMap<>();
        try {
            // 1.判断任务是否存在(分片存储到临时目录,临时目录应定时清空,以防被垃圾分片占满,完成了再拉下来合并)
            if (Boolean.FALSE.equals(redisUtil.hasKey(taskName))) {
                allRecordMap = new HashMap<>();
            } else {
                String taskJson = redisUtil.get(taskName, String.class);
                if (StringUtils.isNotBlank(taskJson)) {
                    allRecordMap = (Map<String, String>) JSONUtil.toBean(taskJson, Map.class);
                }
            }


            // 如果文件片存在,则认为本次是重新上传
            String recordJson = allRecordMap.get(dto.getUploadNum().toString());
            if (StringUtils.isNotBlank(recordJson)) {
                // 删除旧的文件
                FileUtil.deleteFile(filePath);
            }


            // 2.保存分片到临时目录
            FileUtil.uploadSingleFile(dto.getMultipartFile(), filePath);

            // 2.1 记录本次分片上传
            dto.setStatus(true);
            allRecordMap.put(dto.getUploadNum().toString(), JSONUtil.toJsonStr(dto));
            Boolean result = redisUtil.set(taskName, JSONUtil.toJsonStr(allRecordMap), 1L, TimeUnit.DAYS);
            if (Boolean.FALSE.equals(result)) {
                throw new CommonException("记录本次操作失败");
            }

            // 3.判断 文件切片上传成功数===文件总切片数,合并切片到成品目录,返回文件上传成功
            int successNum = 0;
            List<ImageFileBreakpointResumeDTO> fileList = new ArrayList<>();
            for (Map.Entry<String, String> entry : allRecordMap.entrySet()) {
                String json = entry.getValue();
                ImageFileBreakpointResumeDTO bean = JSONUtil.toBean(json, ImageFileBreakpointResumeDTO.class);
                if (Boolean.TRUE.equals(bean.getStatus())) {
                    successNum++;
                    fileList.add(bean);
                }
            }

            if (successNum == dto.getNumTotal()) {
                fileList.sort(Comparator.comparingInt(ImageFileBreakpointResumeDTO::getUploadNum));
                File finishFile = new File(path + "/" + dto.getFileName());
                if (finishFile.exists()) {
                    // 如果存在则先删除
                    FileUtils.forceDelete(finishFile);
                }
                for (ImageFileBreakpointResumeDTO item : fileList) {
                    File itemFile = new File(item.getFilePath());
                    FileUtils.writeByteArrayToFile(finishFile, Files.toByteArray(itemFile), true);
                    // 删除临时文件
                    FileUtils.forceDelete(itemFile);
                }

                // 删除上传任务
                redisUtil.del(taskName);

                return finishFile.getPath();
            }

        } catch (Exception e) {
            dto.setStatus(false);
            allRecordMap.put(dto.getUploadNum().toString(), JSONUtil.toJsonStr(dto));
            redisUtil.set(taskName, JSONUtil.toJsonStr(allRecordMap), 1L, TimeUnit.DAYS);
            LogTraceUtil.error(e);
            throw new CommonException("上传任务失败", e.getMessage());
        } finally {
            System.out.println("--------------------------");
            System.out.println(JSONUtil.toJsonStr(dto));
        }
        return null;
    }


    public static File[] splitFile(File file, int numberOfShards) throws IOException {
        long fileSize = file.length();
        long shardSize = fileSize / numberOfShards;
        long remainder = fileSize % numberOfShards;

        File[] shards = new File[numberOfShards];
        File shardDir = new File("D:\\work\\shards");
        if (!shardDir.exists()) {
            shardDir.mkdirs();
        }

        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];

            for (int i = 0; i < numberOfShards; i++) {
                File shardFile = new File(shardDir, "shard_" + (i + 1) + ".part");
                shards[i] = shardFile;

                try (FileOutputStream fos = new FileOutputStream(shardFile)) {
                    long bytesToWrite = shardSize;
                    if (remainder > 0) {
                        bytesToWrite++;
                        remainder--;
                    }

                    long bytesCopied = 0;
                    while (bytesCopied < bytesToWrite) {
                        int bytesReadThisTime = fis.read(buffer, 0, (int) Math.min(buffer.length, bytesToWrite - bytesCopied));
                        if (bytesReadThisTime == -1) {
                            throw new IOException("Unexpected end of file while writing shard " + (i + 1));
                        }
                        fos.write(buffer, 0, bytesReadThisTime);
                        bytesCopied += bytesReadThisTime;
                    }
                }
            }
        }

        return shards;
    }

    @Override
    public void test() {
        File fileToSplit = new File("D:\\work\\凯通科技-协同子系统\\distributed\\协同构建子系统-界面原型.rp");
        //File fileToSplit = new File("C:\\Users\\kewenyang\\Desktop\\index.vue");
        try {
            int index = 4;
            File[] shards = splitFile(fileToSplit, index);
            String id = UUID.randomUUID().toString();
            for (int i = 0; i < index; i++) {
                File shard = shards[i];
                MultipartFile multipartFile = IMultipartFileImpl.fileToMultipartFile(shard, MediaType.APPLICATION_OCTET_STREAM_VALUE);
                if (multipartFile.getSize() <= 0) {
                    continue;
                }
                ImageFileBreakpointResumeDTO dto = new ImageFileBreakpointResumeDTO();
                dto.setUploadNum(i);
                dto.setNamespace("www.baidu.com");
                dto.setName("baidu");
                dto.setVersion("1.0.0");
                dto.setTaskId(id);
                dto.setMultipartFile(multipartFile);
                dto.setNumTotal(index);
                dto.setFileName("协同构建子系统-界面原型.rp");
                //dto.setFileName("index.vue");
                this.breakpointResumeFile(dto);
                System.out.println("Shard created: " + shard.getAbsolutePath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void clearItemFile() {
        Path rootDir = Paths.get("/imageBreakpointResumeStorage/");
        try {
            java.nio.file.Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.toString().endsWith(".part")) {
                        java.nio.file.Files.delete(file);
                        System.out.println("Deleted file: " + file);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                    // 如果在访问目录内容之前对其进行处理,可以在这里添加逻辑。
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) {
                    System.err.println("Failed to visit file: " + file + " (reason: " + exc.getMessage() + ")");
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new CommonException("执行定时清除分片文件失败");
        }
    }

工具类:

redisUtil

java 复制代码
import cn.hutool.json.JSONObject;
import com.cttnet.common.util.LogTraceUtil;
import com.cttnet.microservices.techteam.distributed.deploy.exception.CommonException;
import com.google.common.collect.Lists;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis 工具类
 *
 * @author kwy
 * @date 2024/11/20
 */
@Component
@Slf4j
public class RedisUtil {
    @Resource
    private ModelMapper modelMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    // =============================common============================

    /**
     * 指定缓存失效时间
     *
     * @param key    缓存的键
     * @param second 缓存失效时间(秒)
     * @return 设置是否成功
     */
    public Boolean expire(String key, Long second) {
        return expire(key, second, TimeUnit.SECONDS);
    }

    /**
     * 指定缓存失效时间
     *
     * @param key      缓存的键
     * @param time     缓存失效时间
     * @param timeUnit 时间单位
     * @return 设置是否成功
     */
    public Boolean expire(String key, Long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);

    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public Boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }
        return false;
    }

    /**
     * 设置字符串键值对。
     * 如果提供的值为null,则将其视为空字符串""进行处理。
     *
     * @param key   键名,指定要设置的Redis键。
     * @param value 值,如果为null,则设置为空字符串""。
     * @return 如果设置成功,则返回true;如果设置失败(例如由于异常),则返回false。
     */
    public Boolean set(String key, Object value) {
        try {
            value = null == value ? "" : value;
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * 设置带有过期时间的字符串键值对。
     *
     * @param key      键名,指定要设置的Redis键。
     * @param value    值,如果值为null,则默认设置为空字符串""。
     * @param time     过期时间。
     * @param timeUnit 时间单位。
     * @return 如果设置成功,则返回true;如果设置失败(例如由于异常),则返回false。
     */
    public Boolean set(String key, Object value, Long time, TimeUnit timeUnit) {
        try {
            value = null == value ? "" : value;
            redisTemplate.opsForValue().set(key, value, time, timeUnit);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(Lists.newArrayList(key));
            }
        }
    }

    /**
     * 删除对应的value
     */
    public void remove(final String key) {
        if (Boolean.TRUE.equals(exists(key))) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 删除hash结构中的某个字段
     */
    public void hashDel(final String key, String item) {
        if (Boolean.TRUE.equals(exists(key))) {
            redisTemplate.opsForHash().delete(key, item);
        }
    }


    /**
     * 判断缓存中是否有对应的value
     */
    public Boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    // ============================String=============================

    /**
     * 设置 String 类型键值对。
     *
     * @param key   键名。
     * @param value 值,如果值为空或仅包含空白字符,则将其设置为空字符串。
     * @return 设置成功返回 true,否则返回 false。
     */
    public Boolean strSet(String key, String value) {
        try {
            value = StringUtils.isBlank(value) ? "" : value;
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * 设置带过期时间的 String 类型键值对。
     *
     * @param key      键名。
     * @param value    值,如果值为空或仅包含空白字符,则将其设置为空字符串。
     * @param time     过期时间。
     * @param timeUnit 时间单位。
     * @return 设置成功返回 true,否则返回 false。
     */
    public Boolean strSet(String key, String value, Long time, TimeUnit timeUnit) {
        try {
            value = StringUtils.isBlank(value) ? "" : value;
            redisTemplate.opsForValue().set(key, value, time, timeUnit);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * 根据给定的键名从 Redis 中获取对应的值。
     *
     * @param key 键名。
     * @return 如果键名存在,则返回对应的值;如果键名不存在或键名为空,则返回 null。
     */
    public Object get(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }

        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 根据给定的键名从 Redis 中获取对应的值,并将该值转换为指定类型的对象。
     * 如果值不是基本数据类型(String、Integer、Double、Byte),则使用 JSON 反序列化将其转换为指定类型的对象。
     *
     * @param key   键名。
     * @param clazz 指定转换后的对象类型。
     * @return 如果键名存在,则返回对应的对象;如果键名不存在或键名为空,则返回 null。
     */
    public <T> T get(String key, Class<T> clazz) {
        if (StringUtils.isBlank(key)) {
            return null;
        }

        if (clazz.equals(String.class)
                || clazz.equals(Integer.class)
                || clazz.equals(Double.class)
                || clazz.equals(Byte.class)) {
            return (T) redisTemplate.opsForValue().get(key);
        }

        JSONObject jsonObject = (JSONObject) redisTemplate.opsForValue().get(key);
        if (null == jsonObject) {
            return null;
        }
        return jsonObject.toBean(clazz);
    }

    /**
     * 对存储在指定键的数值执行原子递增操作。
     *
     * @param key   键名,指定要递增的 Redis 键。
     * @param delta 递增量,表示要增加的值(必须大于0)。
     * @return 递增后的值。
     * @throws RuntimeException 如果递增量小于等于0,则抛出此异常。
     */
    public Long incr(String key, Long delta) {
        if (delta < 0) {
            throw new CommonException("递增因子必须大于0");
        }

        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 对存储在指定键的数值执行原子递减操作。
     *
     * @param key   键名,指定要递减的 Redis 键。
     * @param delta 递减量,表示要减少的值(必须大于0)。
     * @return 递减后的值。
     * @throws RuntimeException 如果递减量小于等于0,则抛出此异常。
     */
    public Long decr(String key, Long delta) {
        if (delta < 0) {
            throw new CommonException("递减因子必须大于0");
        }

        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public <K, V> Map<K, V> hmget(String key, Class<K> k, Class<V> v) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        return (Map<K, V>) entries;
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key   键
     * @param clazz 类
     * @return 对应的多个键值
     */
    public <T> T hmget(String key, Class<T> clazz) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        return modelMapper.map(entries, clazz);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public Boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public Boolean hmset(String key, Map<String, Object> map, Long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * HashSet 并设置时间
     *
     * @param key      键
     * @param map      对应多个键值
     * @param time     时间
     * @param timeUnit 单位
     * @return true成功 false失败
     */
    public Boolean hmset(String key, Map<String, Object> map, Long time, TimeUnit timeUnit) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public Boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public Boolean hset(String key, String item, Object value, Long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
        }

        return false;
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public Boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * 对存储在指定键的哈希表中某个字段的值执行原子递增操作。
     * 如果哈希表或字段不存在,则会创建一个新的哈希表或字段,并将值初始化为0,然后执行递增操作。
     *
     * @param key  键名,指定要操作的 Redis 哈希表键。
     * @param item 字段名,指定要递增的哈希表字段。
     * @param by   递增量,表示要增加的值(必须大于0)。
     * @return 递增后的值。
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return 递减后的值。
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return 返回一个包含集合中所有元素的集合。如果发生异常,则返回 null。
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public Boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public Long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return 0L;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param second 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public Long sSetAndTime(String key, Long second, Object... values) {
        return sSetAndTime(key, second, TimeUnit.SECONDS, values);
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public Long sSetAndTime(String key, Long time, TimeUnit timeUnit, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return count;
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return 0L;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return 返回集合中元素的数量。如果发生异常,则返回 0。
     */
    public Long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return 0L;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public Long setRemove(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return 0L;
        }
    }

    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return 返回一个包含指定范围内元素的列表。如果发生异常,则返回 null。
     */
    public List<Object> lGet(String key, Long start, Long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return 返回列表中元素的数量。如果发生异常,则返回 0。
     */
    public Long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return 0L;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return 返回指定索引处的元素值。如果索引超出范围或发生异常,则返回 null。
     */
    public Object lGetIndex(String key, Long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return null;
        }
    }

    /**
     * 将单个对象添加到 Redis 列表的右侧。
     *
     * @param key   键名,指定要操作的 Redis 列表键。
     * @param value 要添加到列表末尾的对象。
     * @return 如果操作成功,则返回 true;否则返回 false。
     */
    public Boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return 如果操作成功,则返回 true;否则返回 false。
     */

    public Boolean lSet(String key, Object value, Long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public Boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return 如果操作成功,则返回 true;否则返回 false。
     */
    public Boolean lSet(String key, List<Object> value, Long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return 如果操作成功,则返回 true;否则返回 false。
     */
    public Boolean lUpdateIndex(String key, Long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public Long lRemove(String key, Long count, Object value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            LogTraceUtil.error(e);
            return 0L;
        }
    }


    /**
     * 获取固定前缀的key
     *
     * @param suffix 键名的后缀,用于匹配所有以该后缀开头的键名。
     * @return 一个包含所有匹配键名的集合。
     */
    public Set<String> getKeySuffix(String suffix) {
        return redisTemplate.keys(suffix + ":*");
    }


}

文件转换类(用于本地测试)

java 复制代码
import com.cttnet.microservices.techteam.distributed.deploy.exception.CommonException;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * 负责将InputStream转换MultipartFile,可以少引一个jar包,本来用的是spring-test-5.2.8中的MockMultipartFile,直接提取出来使用
 * 见 https://blog.csdn.net/m0_37609579/article/details/100901358
 *
 * @author kwy
 * @date 2024/11/20
 */
public class IMultipartFileImpl implements MultipartFile {

    /**
     * 文件名称
     */
    private final String name;

    /**
     * 原始文件名
     */
    private final String originalFilename;

    /**
     * 文件内容类型
     */
    @Nullable
    private final String contentType;


    /**
     * 文件内容字节数组
     */
    private final byte[] content;


    /**
     * Create a new MockMultipartFile with the given content.
     *
     * @param name    the name of the file
     * @param content the content of the file
     */
    public IMultipartFileImpl(String name, @Nullable byte[] content) {
        this(name, "", null, content);
    }

    /**
     * Create a new MockMultipartFile with the given content.
     *
     * @param name          the name of the file
     * @param contentStream the content of the file as stream
     * @throws IOException if reading from the stream failed
     */
    public IMultipartFileImpl(String name, InputStream contentStream) throws IOException {
        this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));
    }

    /**
     * Create a new MockMultipartFile with the given content.
     *
     * @param name             the name of the file
     * @param originalFilename the original filename (as on the client's machine)
     * @param contentType      the content type (if known)
     * @param content          the content of the file
     */
    public IMultipartFileImpl(String name, @Nullable String originalFilename, @Nullable String contentType, @Nullable byte[] content) {

        Assert.hasLength(name, "Name must not be empty");
        this.name = name;
        this.originalFilename = (originalFilename != null ? originalFilename : "");
        this.contentType = contentType;
        this.content = (content != null ? content : new byte[0]);
    }

    /**
     * Create a new MockMultipartFile with the given content.
     *
     * @param name             the name of the file
     * @param originalFilename the original filename (as on the client's machine)
     * @param contentType      the content type (if known)
     * @param contentStream    the content of the file as stream
     * @throws IOException if reading from the stream failed
     */
    public IMultipartFileImpl(
            String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream)
            throws IOException {

        this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
    }


    @Override
    public String getName() {
        return this.name;
    }

    @Override
    @NonNull
    public String getOriginalFilename() {
        return this.originalFilename;
    }

    @Override
    @Nullable
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return (this.content.length == 0);
    }

    @Override
    public long getSize() {
        return this.content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return this.content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.content);
    }

    @Override
    public void transferTo(File dest) throws IOException {
        FileCopyUtils.copy(this.content, dest);
    }

    /**
     * File 转 MultipartFile 用完不删
     *
     * @param file        {@linkplain File}
     * @param contentType 内容类型
     * @return {@linkplain MultipartFile}
     */
    public static MultipartFile fileToMultipartFile(File file, String contentType) {
        try {
            return new IMultipartFileImpl("file", file.getName(), contentType, Files.newInputStream(file.toPath()));
        } catch (Exception e) {
            throw new CommonException("File 转 MultipartFile失败!" + e.getMessage());
        }
    }
}

以上代码有后端测试断点续传的接口,本地启动项目,可以直接测试使用,所以如果前端说你有问题,怼他即可。前端实现逻辑,照着后端测试方法的思路实现即可,记录上传分片序号,计算获得上传进度。

如果白嫖过程中发现遗漏或问题的,请在评论区留言,我看到会修正或补充。

相关推荐
zhangfeng11331 小时前
openclaw skills 小龙虾技能 通讯仿真 matlab skill Simulink Agentic Toolkit,通过kimi找到,mcp通讯
开发语言·matlab·openclaw·通讯仿真
Javatutouhouduan8 小时前
2026Java面试的正确打开方式!
java·高并发·java面试·java面试题·后端开发·java编程·java八股文
chao1898448 小时前
基于 SPEA2 的多目标优化算法 MATLAB 实现
开发语言·算法·matlab
JAVA面经实录9178 小时前
Java初级最终完整版学习路线图
java·spring·eclipse·maven
赏金术士8 小时前
Kotlin 习题集 · 高级篇
android·开发语言·kotlin
Cat_Rocky9 小时前
k8s-持久化存储,粗浅学习
java·学习·kubernetes
楼兰公子9 小时前
buildroot 在编译rust时裁剪平台类型数量的方法
开发语言·后端·rust
知识领航员10 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github
吴声子夜歌10 小时前
Go——并发编程
开发语言·后端·golang
释怀°Believe10 小时前
Spring解析
java·后端·spring