forceUpdateJsonFields 方法说明
forceUpdateJsonFields 方法说明
/**
* 强制更新JSON数据中的多个字段值(批量处理)
* @param dbIndex 数据库索引
* @param dataList 需要更新的数据列表,每个元素必须包含标识key的字段(如"f12")
* @param allowNewKeys 是否允许新增不存在的key
* @return 更新结果统计:成功更新数, 新增数, 失败数
*/
public static int[] forceUpdateJsonFields(int dbIndex, List<JSONObject> dataList, boolean allowNewKeys) {
return getInstance()._forceUpdateJsonFields(dbIndex, dataList, allowNewKeys);
}
/**
* 内部实现 - 强制更新JSON数据中的多个字段值(批量处理)
* @param dbIndex 数据库索引
* @param dataList 需要更新的数据列表
* @param allowNewKeys 是否允许新增不存在的key
* @return 更新结果统计:成功更新数, 新增数, 失败数
*/
private int[] _forceUpdateJsonFields(int dbIndex, List<JSONObject> dataList, boolean allowNewKeys) {
int[] stats = new int[3]; // [updatedCount, newCount, errorCount]
if (dataList == null || dataList.isEmpty()) {
System.out.println("No data to update");
return stats;
}
try (Jedis jedis = _selectDb(_getJedis(), dbIndex)) {
// 批量处理模式
Pipeline pipeline = jedis.pipelined();
Map<String, Response<String>> responses = new HashMap<>();
// 1. 先批量获取所有key的当前值
for (JSONObject data : dataList) {
String key = data.getStr("f12"); // 假设使用f12作为key
responses.put(key, pipeline.get(key));
}
pipeline.sync();
// 2. 处理每个数据项
for (JSONObject newData : dataList) {
String key = newData.getStr("f12");
try {
// 获取该key的当前值
String currentValue = responses.get(key).get();
if (currentValue != null && currentValue.startsWith("{")) {
// 已有数据 - 合并更新
JSONObject currentJson = new JSONObject(currentValue);
newData.forEach(currentJson::set);
pipeline.set(key, currentJson.toString());
stats[0]++; // 更新计数
} else if (allowNewKeys) {
// 新增数据
pipeline.set(key, newData.toString());
stats[1]++; // 新增计数
}
} catch (Exception e) {
stats[2]++; // 错误计数
System.err.println("Error processing key: " + key + ", Error: " + e.getMessage());
}
}
// 3. 执行批量更新
pipeline.sync();
} catch (Exception e) {
System.err.println("Batch update error: " + e.getMessage());
e.printStackTrace();
stats[2] = dataList.size(); // 标记全部失败
}
return stats;
}
主要变化:
-
改为批量处理模式,使用Redis pipeline提高性能
-
参数改为接收JSON对象列表和allowNewKeys标志
-
返回包含更新统计结果的数组
-
保持与参考代码相同的字段更新逻辑(合并现有JSON)
-
使用"f12"作为key字段名以保持一致性
同时保留原来的单key更新方法作为重载:
/**
* 强制更新单个key的JSON字段值
* @param dbIndex 数据库索引
* @param key Redis键
* @param fieldUpdates 要更新的字段及新值
* @return 1表示更新成功,0表示无更新或key不存在,-1表示错误
*/
public static int forceUpdateJsonFields(int dbIndex, String key, Map<String, Object> fieldUpdates) {
return getInstance()._forceUpdateJsonFields(dbIndex, key, fieldUpdates);
}
int dbIndex = 0; // 假设使用数据库0 List<JSONObject> dataList = ...; // 你的数据列表 boolean allowNewKeys = true; // 是否允许新增key // 调用批量更新方法 int[] updateStats = forceUpdateJsonFields(dbIndex, dataList, allowNewKeys); // 解析结果 int updatedCount = updateStats[0]; // 成功更新数 int newCount = updateStats[1]; // 新增数量 int errorCount = updateStats[2]; // 失败数量
浙公网安备 33010602011771号