HuahengRedisUtils.java 32.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
package com.huaheng.control.management.utils;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.huaheng.control.management.dto.EquipmentStatus;
import com.huaheng.control.management.dto.Task;
import com.huaheng.control.management.dto.TaskExecutionOrder;
import com.huaheng.control.management.utils.constant.CommonConstant;

import lombok.extern.slf4j.Slf4j;

/**
 * Redis缓存操作工具类
 * @author     TanYibin
 * @createDate 2023年2月8日
 */
@Slf4j
@Component
public class HuahengRedisUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static String toJsonString(Object obj) {
        if (obj == null) {
            return null;
        } else {
            return JSON.toJSONString(obj);
        }
    }

    private static <T> T parseObject(String jsonString, Class<T> cls) {
        return JSON.parseObject(jsonString, cls);
    }

    private static <T> T parseObject(String jsonString, TypeReference<T> type) {
        return JSON.parseObject(jsonString, type);
    }

    /**
     * 将key中存储值的整数值递增1,返回递增后的值
     * @author             TanYibin
     * @createDate         2023年2月8日
     * @param      key
     * @param      seconds 过期时间(秒)
     * @return
     */
    public Long incr(@NonNull String key, @NonNull Integer seconds) {
        try {
            Long returnValue = stringRedisTemplate.opsForValue().increment(key);
            if (returnValue.equals(1l)) {
                stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return returnValue;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return null;
    }

    /**
     * 将key中存储值的整数值递减1,返回递减后的值
     * @author             TanYibin
     * @createDate         2023年2月8日
     * @param      key
     * @param      seconds 过期时间(秒)
     * @return
     */
    public Long decr(@NonNull String key, @NonNull Integer seconds) {
        try {
            Long returnValue = stringRedisTemplate.opsForValue().decrement(key);
            if (returnValue.equals(-1l)) {
                stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return returnValue;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return null;
    }

    /**
     * 设置key,value(过期时间:2小时)
     * @author           TanYibin
     * @createDate       2023年2月8日
     * @param      key
     * @param      value
     */
    public boolean set(@NonNull String key, @NonNull Object value) {
        try {
            stringRedisTemplate.opsForValue().set(key, toJsonString(value), Duration.ofHours(2));
            return true;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return false;
    }

    /**
     * 设置key,value(无过期时间)
     * @author           TanYibin
     * @createDate       2023年2月8日
     * @param      key
     * @param      value
     */
    public boolean setWithNoExpirationTime(@NonNull String key, @NonNull Object value) {
        try {
            stringRedisTemplate.opsForValue().set(key, toJsonString(value));
            return true;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return false;
    }

    /**
     * 设置key,value,过期时间
     * @author             TanYibin
     * @createDate         2023年2月8日
     * @param      key
     * @param      value
     * @param      seconds 过期时间(秒)
     */
    public boolean set(@NonNull String key, @NonNull Object value, @NonNull Integer seconds) {
        try {
            stringRedisTemplate.opsForValue().set(key, toJsonString(value), seconds, TimeUnit.SECONDS);
            return true;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return false;
    }

    /**
     * 将key的值设置为value,并且返回原key的值(过期时间:2小时)
     * @author           TanYibin
     * @createDate       2026年1月5日
     * @param      <T>
     * @param      key
     * @param      value
     * @param      clazz
     * @return
     */
    public <T> T getAndSet(@NonNull String key, @NonNull T value, @NonNull Class<T> clazz) {
        try {
            String jsonString = stringRedisTemplate.opsForValue().getAndSet(key, toJsonString(value));
            stringRedisTemplate.expire(key, Duration.ofHours(2));
            if (StringUtils.isEmpty(jsonString)) {
                return null;
            }
            return parseObject(jsonString, clazz);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return null;
    }

    /**
     * 将key的值设置为value,并且返回原key的值(过期时间:2小时)
     * @author           TanYibin
     * @createDate       2026年1月5日
     * @param      <T>
     * @param      key
     * @param      value
     * @param      type
     * @return
     */
    public <T> T getAndSet(@NonNull String key, @NonNull T value, @NonNull TypeReference<T> type) {
        try {
            String jsonString = stringRedisTemplate.opsForValue().getAndSet(key, toJsonString(value));
            stringRedisTemplate.expire(key, Duration.ofHours(2));
            if (StringUtils.isEmpty(jsonString)) {
                return null;
            }
            return parseObject(jsonString, type);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return null;
    }

    /**
     * 将key的值设置为value,并且返回原key的值
     * @author             TanYibin
     * @createDate         2026年1月5日
     * @param      <T>
     * @param      key
     * @param      value
     * @param      type
     * @param      seconds 过期时间(秒)
     * @return
     */
    public <T> T getAndSet(@NonNull String key, @NonNull T value, @NonNull TypeReference<T> type, @NonNull Integer seconds) {
        try {
            String jsonString = stringRedisTemplate.opsForValue().getAndSet(key, toJsonString(value));
            stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            if (StringUtils.isEmpty(jsonString)) {
                return null;
            }
            return parseObject(jsonString, type);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return null;
    }

    /**
     * 设置key的过期时间
     * @author             TanYibin
     * @createDate         2023年2月8日
     * @param      key
     * @param      seconds
     * @return
     */
    public boolean expire(@NonNull String key, @NonNull Integer seconds) {
        try {
            return stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return false;
    }

    /**
     * 获取key的过期时间
     * @author         TanYibin
     * @createDate     2023年2月8日
     * @param      key
     * @return
     */
    public long getExpire(@NonNull String key) {
        try {
            return stringRedisTemplate.getExpire(key);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception ex) {
            log.error("操作缓存异常:Key:{}", key, ex);
        }
        return 0;
    }

    /**
     * 获取key的值
     * @author           TanYibin
     * @createDate       2023年2月8日
     * @param      <T>
     * @param      key
     * @param      clazz
     * @return
     */
    public <T> T get(@NonNull String key, @NonNull Class<T> clazz) {
        try {
            String result = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isEmpty(result)) {
                return null;
            }
            return parseObject(result, clazz);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return null;
    }

    /**
     * 获取key的值
     * @author         TanYibin
     * @createDate     2023年2月8日
     * @param      <T>
     * @param      key
     * @return
     */
    public <T> T get(@NonNull String key, @NonNull TypeReference<T> type) {
        try {
            String result = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isEmpty(result)) {
                return null;
            }
            return parseObject(result, type);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return null;
    }

    /**
     * 删除key
     * @author         TanYibin
     * @createDate     2023年2月8日
     * @param      key
     */
    public boolean delete(@NonNull String key) {
        try {
            return stringRedisTemplate.delete(key);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return false;
    }

    /**
     * 判断是否有key对应的值,有则返回true,没有则返回false
     * @author         TanYibin
     * @createDate     2023年2月8日
     * @param      key
     * @return
     */
    public boolean hasKey(@NonNull String key) {
        try {
            return stringRedisTemplate.hasKey(key);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", key, e);
        }
        return false;
    }

    /**
     * 存储任务信息
     * @param taskId 任务ID
     * @param status 状态
     * @param data   该状态对应的数据
     */
    public boolean saveTask(String taskId, String status, Task task) {
        try {
            String redisKey = CommonConstant.CMC_TASK_KEY_PREFIX + taskId;
            // 将数据转换为JSON字符串存储,保持格式统一
            String dataJson = toJsonString(task);
            stringRedisTemplate.opsForHash().put(redisKey, status, dataJson);
            return true;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("存储任务数据异常:taskId: {}, status: {}", taskId, status, e);
        }
        return false;
    }

    /**
     * 根据任务ID和状态获取任务信息
     * @param  taskId 任务ID
     * @param  status 状态
     * @return        该状态下的信息
     */
    public Task getTask(String taskId, String status) {
        String redisKey = CommonConstant.CMC_TASK_KEY_PREFIX + taskId;
        try {
            String result = (String)stringRedisTemplate.opsForHash().get(redisKey, status);
            if (StringUtils.isEmpty(result)) {
                return null;
            }
            return parseObject(result, Task.class);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("获取任务数据异常:Key:{}", redisKey, e);
        }
        return null;
    }

    /**
     * 存储历史任务信息
     * @param taskId 任务ID
     * @param status 状态
     * @param data   该状态对应的数据
     */
    public boolean saveHistoryTaskDetail(String taskId) {
        try {
            String redisKey = CommonConstant.CMC_TASK_KEY_PREFIX + taskId;

            Map<Object, Object> taskDetail = stringRedisTemplate.opsForHash().entries(redisKey);
            if (taskDetail.isEmpty()) {
                return false;
            }

            String historyRedisKey = CommonConstant.CMC_HISTORY_TASK_KEY_PREFIX + taskId;

            stringRedisTemplate.opsForHash().putAll(historyRedisKey, taskDetail);
            stringRedisTemplate.expire(historyRedisKey, 30, TimeUnit.DAYS);

            String listKey = CommonConstant.CMC_HISTORY_TASK_KEY_PREFIX + "LIST";

            // 添加到任务ID列表(左侧插入,保持最新在最前)
            stringRedisTemplate.opsForList().leftPush(listKey, historyRedisKey);

            // 限制列表长度(只保留最近1000个)
            stringRedisTemplate.opsForList().trim(listKey, 0, 999);
            stringRedisTemplate.expire(listKey, 30, TimeUnit.DAYS);

            return true;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("存储历史任务信息异常:taskId: {}", taskId, e);
        }
        return false;
    }

    /**
     * 获取最后N条历史任务信息(通过List)
     */
    public Map<String, Map<String, Task>> getLastNHistoryTaskDetails(Long count) {
        Map<String, Map<String, Task>> result = new LinkedHashMap<>();
        try {
            String listKey = CommonConstant.CMC_HISTORY_TASK_KEY_PREFIX + "LIST";

            // 获取前N个任务ID(最新的在最前面)
            List<String> taskKeys = stringRedisTemplate.opsForList().range(listKey, 0, count);

            if (CollectionUtils.isEmpty(taskKeys)) {
                return result;
            }

            // 批量获取任务详情
            return getHistoryTaskDetails(new HashSet<String>(taskKeys));

        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("通过List获取最后10条历史任务信息异常", e);
        }
        return result;
    }

    /**
     * 获取所有任务Key
     * @return 所有任务Key的集合
     */
    public Set<String> getAllTaskKeys() {
        String pattern = CommonConstant.CMC_TASK_KEY_PREFIX + "*";
        Set<String> keys = new HashSet<>();
        try {
            Cursor<byte[]> cursor =
                stringRedisTemplate.executeWithStickyConnection(connection -> connection.scan(ScanOptions.scanOptions().match(pattern).count(1000) // 每次扫描数量
                    .build()));
            while (cursor.hasNext()) {
                keys.add(new String(cursor.next()));
            }
            cursor.close();
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("获取所有任务的Key异常", e);
        }
        return keys;
    }

    /**
     * 获取任务状态数据集合
     * @return 任务状态数据集合
     */
    public Map<String, Map<String, Task>> getAllTaskDetails() {
        return getTaskDetails(getAllTaskKeys());
    }

    /**
     * 获取任务状态数据集合,TaskId为Key
     * @return Map<TaskId, 任务状态数据>
     */
    public Map<String, Map<String, Task>> getTaskDetails(Set<String> taskKeys) {
        Map<String, Map<String, Task>> result = new HashMap<>();
        if (CollectionUtils.isEmpty(taskKeys)) {
            return result;
        }
        try {
            List<Object> taskDetails = stringRedisTemplate.executePipelined((RedisCallback<Object>)connection -> {
                for (String key : taskKeys) {
                    connection.hashCommands().hGetAll(key.getBytes(StandardCharsets.UTF_8)); // 指定字符集
                }
                return null;
            });
            // 将Redis Key转换为TaskId
            int index = 0;
            for (String taskKey : taskKeys) {
                String taskId = taskKey.substring(CommonConstant.CMC_TASK_KEY_PREFIX.length());
                @SuppressWarnings("unchecked")
                Map<String, Task> taskDetail = ((Map<String, String>)taskDetails.get(index)).entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, entry -> JSON.parseObject(entry.getValue(), Task.class)));
                result.put(taskId, taskDetail);
                index++;
            }
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("获取任务数据集合异常", e);
        }
        return result;
    }

    /**
     * 获取历史任务状态数据集合,TaskId为Key
     * @return Map<TaskId, 任务状态数据>
     */
    public Map<String, Map<String, Task>> getHistoryTaskDetails(Set<String> taskKeys) {
        Map<String, Map<String, Task>> result = new HashMap<>();
        if (CollectionUtils.isEmpty(taskKeys)) {
            return result;
        }
        try {
            List<Object> historyTaskDetails = stringRedisTemplate.executePipelined((RedisCallback<Object>)connection -> {
                for (String key : taskKeys) {
                    connection.hashCommands().hGetAll(key.getBytes(StandardCharsets.UTF_8)); // 指定字符集
                }
                return null;
            });
            // 将Redis Key转换为TaskId
            int index = 0;
            for (String taskKey : taskKeys) {
                String historyTaskId = taskKey.substring(CommonConstant.CMC_HISTORY_TASK_KEY_PREFIX.length());
                @SuppressWarnings("unchecked")
                Map<String, Task> historyTaskDetail = ((Map<String, String>)historyTaskDetails.get(index)).entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, entry -> JSON.parseObject(entry.getValue(), Task.class)));
                result.put(historyTaskId, historyTaskDetail);
                index++;
            }
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("获取任务状态数据集合异常", e);
        }
        return result;
    }

    /**
     * 根据状态筛选任务状态数据集合
     * @param  targetStatus 目标状态
     * @return              包含指定状态的任务状态数据集合
     */
    public Map<String, Map<String, Task>> getTaskDetailsByStatus(Set<String> taskKeys, String targetStatus) {
        Map<String, Map<String, Task>> taskDetails = getTaskDetails(taskKeys);
        Map<String, Map<String, Task>> matchedTasks = new HashMap<>();
        for (Entry<String, Map<String, Task>> entry : taskDetails.entrySet()) {
            String taskId = entry.getKey();
            Map<String, Task> taskDetail = entry.getValue();
            if (taskDetail.containsKey(targetStatus)) {
                matchedTasks.put(taskId, taskDetail);
            }
        }
        return matchedTasks;
    }

    /**
     * 根据任务ID获取任务数据
     * @param  taskId 任务ID
     * @return        包含所有状态数据的Map
     */
    public Map<String, Task> getTaskDetail(String taskId) {
        String redisKey = CommonConstant.CMC_TASK_KEY_PREFIX + taskId;
        try {
            Map<Object, Object> taskDetail = stringRedisTemplate.opsForHash().entries(redisKey);
            if (taskDetail.isEmpty()) {
                return null;
            }
            return taskDetail.entrySet().stream().filter(entry -> entry.getKey() != null && entry.getValue() != null)
                .collect(Collectors.toMap(entry -> entry.getKey().toString(), entry -> JSON.parseObject(entry.getValue().toString(), Task.class),
                    (existing, replacement) -> existing, LinkedHashMap::new));
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", redisKey, e);
            return null;
        }
    }

    /**
     * 根据任务ID获取历史任务数据
     * @param  taskId 任务ID
     * @return        包含所有状态数据的Map
     */
    public Map<String, Task> getHistoryTaskDetail(String taskId) {
        String redisKey = CommonConstant.CMC_HISTORY_TASK_KEY_PREFIX + taskId;
        try {
            Map<Object, Object> historyTaskDetail = stringRedisTemplate.opsForHash().entries(redisKey);
            if (historyTaskDetail.isEmpty()) {
                return null;
            }
            return historyTaskDetail.entrySet().stream().filter(entry -> entry.getKey() != null && entry.getValue() != null)
                .collect(Collectors.toMap(entry -> entry.getKey().toString(), entry -> JSON.parseObject(entry.getValue().toString(), Task.class),
                    (existing, replacement) -> existing, LinkedHashMap::new));
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", redisKey, e);
            return null;
        }
    }

    /**
     * 删除整个任务数据
     * @param taskId 任务ID
     */
    public boolean deleteTaskDetail(String taskId) {
        String redisKey = CommonConstant.CMC_TASK_KEY_PREFIX + taskId;
        try {
            return stringRedisTemplate.delete(redisKey);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", redisKey, e);
        }
        return false;
    }

    /**
     * 保存任务执行顺序(完全覆盖)
     * @param  taskExecutionOrders 任务执行顺序列表
     * @return                     保存成功的数量
     */
    public int saveTaskExecutionOrders(List<TaskExecutionOrder> taskExecutionOrders) {
        if (CollectionUtils.isEmpty(taskExecutionOrders)) {
            log.warn("任务执行顺序列表为空");
            return 0;
        }
        try {
            // 验证数据有效性
            List<TaskExecutionOrder> validOrders = taskExecutionOrders.stream().filter(TaskExecutionOrder::isValid).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(validOrders)) {
                log.warn("无有效的任务执行顺序数据");
                return 0;
            }
            // 创建 Redis 有序集合的元组
            Set<ZSetOperations.TypedTuple<String>> tuples = validOrders.stream()
                .map(order -> ZSetOperations.TypedTuple.of(order.getTaskId(), order.getTaskExecutionOrder().doubleValue())).collect(Collectors.toSet());
            // 先删除旧的,再添加新的(完全覆盖)
            stringRedisTemplate.delete(CommonConstant.CMS_TASK_ORDER_KEY);
            Long addedCount = stringRedisTemplate.opsForZSet().add(CommonConstant.CMS_TASK_ORDER_KEY, tuples);

            int result = addedCount != null ? addedCount.intValue() : 0;
            log.info("保存任务执行顺序成功,数量: {}", result);

            return result;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("保存任务执行顺序异常", e);
            return 0;
        }
    }

    /**
     * 增量更新任务执行顺序(不删除已有数据)
     * @param  taskExecutionOrders 任务执行顺序列表
     * @return                     更新成功的数量
     */
    public int updateTaskExecutionOrders(List<TaskExecutionOrder> taskExecutionOrders) {
        if (CollectionUtils.isEmpty(taskExecutionOrders)) {
            log.warn("任务执行顺序列表为空");
            return 0;
        }

        try {
            // 验证数据有效性
            List<TaskExecutionOrder> validOrders = taskExecutionOrders.stream().filter(TaskExecutionOrder::isValid).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(validOrders)) {
                log.warn("无有效的任务执行顺序数据");
                return 0;
            }

            // 创建 Redis 有序集合的元组
            Set<ZSetOperations.TypedTuple<String>> tuples = validOrders.stream()
                .map(order -> ZSetOperations.TypedTuple.of(order.getTaskId(), order.getTaskExecutionOrder().doubleValue())).collect(Collectors.toSet());

            // 增量添加(不删除已有数据)
            Long addedCount = stringRedisTemplate.opsForZSet().add(CommonConstant.CMS_TASK_ORDER_KEY, tuples);

            int result = addedCount != null ? addedCount.intValue() : 0;
            log.info("更新任务执行顺序成功,数量: {}", result);

            return result;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("更新任务执行顺序异常", e);
            return 0;
        }
    }

    /**
     * 获取所有任务执行顺序(按顺序排序),返回Map格式
     * @return Map<taskId, 执行顺序>
     */
    public Map<String, Integer> getAllTaskExecutionOrderMap() {
        try {
            Set<ZSetOperations.TypedTuple<String>> tuples = stringRedisTemplate.opsForZSet().rangeWithScores(CommonConstant.CMS_TASK_ORDER_KEY, 0, -1);
            if (CollectionUtils.isEmpty(tuples)) {
                return new LinkedHashMap<>(); // 使用LinkedHashMap保持插入顺序
            }
            // 转换为Map<taskId, 执行顺序>,并按执行顺序排序
            Map<String, Integer> result = tuples.stream().sorted(Comparator.comparingDouble(ZSetOperations.TypedTuple::getScore)).collect(
                Collectors.toMap(ZSetOperations.TypedTuple::getValue, tuple -> tuple.getScore().intValue(), (oldValue, newValue) -> oldValue, LinkedHashMap::new));
            return result;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("获取所有任务执行顺序异常", e);
            return new LinkedHashMap<>();
        }
    }

    /**
     * 获取前N个任务执行顺序
     * @param  limit 数量限制
     * @return       任务执行顺序列表
     */
    public Map<String, Integer> getTopNTaskExecutionOrders(int limit) {
        try {
            Set<ZSetOperations.TypedTuple<String>> tuples = stringRedisTemplate.opsForZSet().rangeWithScores(CommonConstant.CMS_TASK_ORDER_KEY, 0, limit - 1);
            if (CollectionUtils.isEmpty(tuples)) {
                return new LinkedHashMap<>();
            }
            Map<String, Integer> result = tuples.stream().sorted(Comparator.comparingDouble(ZSetOperations.TypedTuple::getScore)).collect(
                Collectors.toMap(ZSetOperations.TypedTuple::getValue, tuple -> tuple.getScore().intValue(), (oldValue, newValue) -> oldValue, LinkedHashMap::new));
            return result;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("获取前{}个任务执行顺序异常", limit, e);
            return new LinkedHashMap<>();
        }
    }

    /**
     * 删除指定任务的执行顺序
     * @param  taskIds 任务ID列表
     * @return         删除的数量
     */
    public int removeTaskExecutionOrders(List<String> taskIds) {
        if (CollectionUtils.isEmpty(taskIds)) {
            return 0;
        }
        try {
            Long removedCount = stringRedisTemplate.opsForZSet().remove(CommonConstant.CMS_TASK_ORDER_KEY, taskIds.toArray());
            return removedCount != null ? removedCount.intValue() : 0;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("删除任务执行顺序异常", e);
            return 0;
        }
    }

    public boolean saveEquipmentStatus(@NotNull String id, EquipmentStatus equipmentStatus) {
        String redisKey = CommonConstant.CMC_EQUIPMENT_STATUS_INFO_KEY;
        // 将数据转换为JSON字符串存储,保持格式统一
        try {
            String dataJson = toJsonString(equipmentStatus);
            stringRedisTemplate.opsForHash().put(redisKey, id, dataJson);
            return true;
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("存储设备状态异常:equipmentID: {}, equipmentStatus: {}", id, equipmentStatus, e);
        }
        return false;
    }

    /**
     * 根据设备ID获取设备状态数据
     */
    public EquipmentStatus getEquipmentStatus(String equipmentId) {
        try {
            String result = (String)stringRedisTemplate.opsForHash().get(CommonConstant.CMC_EQUIPMENT_STATUS_INFO_KEY, equipmentId);
            if (result == null) {
                return null;
            }
            return parseObject(result, EquipmentStatus.class);
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("查询设备状态异常:equipmentId: {}", equipmentId, e);
            return null;
        }
    }

    /**
     * 获取设备状态数据集合
     * @return 设备状态数据Map
     */
    public Map<String, EquipmentStatus> getAllEquipmentStatusMap() {
        String redisKey = CommonConstant.CMC_EQUIPMENT_STATUS_INFO_KEY;
        try {
            Map<Object, Object> equipmentStatusMap = stringRedisTemplate.opsForHash().entries(redisKey);
            if (equipmentStatusMap.isEmpty()) {
                return null;
            }
            return equipmentStatusMap.entrySet().stream().filter(entry -> entry.getKey() != null && entry.getValue() != null)
                .collect(Collectors.toMap(entry -> entry.getKey().toString(), entry -> JSON.parseObject(entry.getValue().toString(), EquipmentStatus.class),
                    (existing, replacement) -> existing, LinkedHashMap::new));
        } catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败", e);
        } catch (Exception e) {
            log.error("操作缓存异常:Key:{}", redisKey, e);
            return null;
        }
    }

}