package com.ard.work.sdk.zlxd.netty.tcp;
|
|
import java.util.Map;
|
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.ConcurrentHashMap;
|
|
public class ResponseFutureHolder {
|
|
// 1. 键改为 String 类型,格式为 "相机ID_序列号"
|
private static final Map<String, CompletableFuture<String>> FUTURE_MAP =
|
new ConcurrentHashMap<>();
|
|
/**
|
* 保存 future(新增重载方法,适配唯一键)
|
* @param uniqueKey 格式:cameraId_seq
|
* @param future 待保存的异步结果
|
*/
|
public static void put(String uniqueKey, CompletableFuture<String> future) {
|
FUTURE_MAP.put(uniqueKey, future);
|
}
|
|
/**
|
* 兼容旧方法(不推荐使用,仅用于过渡)
|
*/
|
@Deprecated
|
public static void put(int seq, CompletableFuture<String> future) {
|
FUTURE_MAP.put(String.valueOf(seq), future);
|
}
|
|
/**
|
* 获取 future(新增重载方法)
|
* @param uniqueKey 格式:cameraId_seq
|
*/
|
public static CompletableFuture<String> get(String uniqueKey) {
|
return FUTURE_MAP.get(uniqueKey);
|
}
|
|
/**
|
* 兼容旧方法(不推荐使用)
|
*/
|
@Deprecated
|
public static CompletableFuture<String> get(int seq) {
|
return FUTURE_MAP.get(String.valueOf(seq));
|
}
|
|
/**
|
* 移除 future(新增重载方法)
|
* @param uniqueKey 格式:cameraId_seq
|
*/
|
public static void remove(String uniqueKey) {
|
FUTURE_MAP.remove(uniqueKey);
|
}
|
|
/**
|
* 兼容旧方法(不推荐使用)
|
*/
|
@Deprecated
|
public static void remove(int seq) {
|
FUTURE_MAP.remove(String.valueOf(seq));
|
}
|
|
/**
|
* 完成并移除(新增重载方法)
|
* @param uniqueKey 格式:cameraId_seq
|
* @param response 响应结果
|
*/
|
public static void complete(String uniqueKey, String response) {
|
CompletableFuture<String> future = FUTURE_MAP.remove(uniqueKey);
|
if (future != null) {
|
future.complete(response);
|
}
|
}
|
|
/**
|
* 兼容旧方法(不推荐使用)
|
*/
|
@Deprecated
|
public static void complete(int seq, String response) {
|
complete(String.valueOf(seq), response);
|
}
|
|
/**
|
* 异常完成并移除(新增重载方法)
|
* @param uniqueKey 格式:cameraId_seq
|
* @param ex 异常信息
|
*/
|
public static void completeExceptionally(String uniqueKey, Throwable ex) {
|
CompletableFuture<String> future = FUTURE_MAP.remove(uniqueKey);
|
if (future != null) {
|
future.completeExceptionally(ex);
|
}
|
}
|
|
/**
|
* 兼容旧方法(不推荐使用)
|
*/
|
@Deprecated
|
public static void completeExceptionally(int seq, Throwable ex) {
|
completeExceptionally(String.valueOf(seq), ex);
|
}
|
|
/**
|
* 新增:按相机ID清理所有相关的Future(断开连接时调用)
|
* @param cameraId 相机ID
|
*/
|
public static void clearByCamera(String cameraId) {
|
// 遍历并移除所有以该相机ID开头的键
|
FUTURE_MAP.keySet().removeIf(key -> key.startsWith(cameraId + "_"));
|
// 打印日志(可选,用于调试)
|
// System.out.println("清理相机[" + cameraId + "]的所有未完成Future");
|
}
|
|
/**
|
* 新增:清空所有Future(应用关闭时调用)
|
*/
|
public static void clearAll() {
|
FUTURE_MAP.clear();
|
}
|
}
|