HuahengRedisUtils.java
18 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
package com.huaheng.control.management.utils;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
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 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.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.Task;
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 saveTaskStatus(String taskId, String status, Object data) {
try {
String redisKey = CommonConstant.CMC_TASK_KEY_PREFIX + taskId;
// 将数据转换为JSON字符串存储,保持格式统一
String dataJson = toJsonString(data);
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 <T> T getTaskDataByStatus(String taskId, String status, @NonNull TypeReference<T> type) {
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, type);
} catch (RedisConnectionFailureException e) {
throw new RuntimeException("Redis连接失败", e);
} catch (Exception e) {
log.error("任务状态数据异常:Key:{}", redisKey, e);
}
return null;
}
/**
* 获取所有任务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 getTaskDetailsWithTaskKeys(getAllTaskKeys());
}
/**
* 获取任务状态数据集合,TaskId为Key
* @return Map<TaskId, 任务状态数据>
*/
@SuppressWarnings("unchecked")
public Map<String, Map<String, Task>> getTaskDetailsWithTaskKeys(Set<String> taskKeys) {
Map<String, Map<String, Task>> result = new HashMap<>();
if (CollectionUtils.isEmpty(taskKeys)) {
return result;
}
try {
List<Object> taskResults = 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());
Map<String, Task> taskResult = ((Map<String, String>)taskResults.get(index)).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> JSON.parseObject(entry.getValue(), Task.class)));
result.put(taskId, taskResult);
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>> getTasksByStatus(Set<String> taskKeys, String targetStatus) {
Map<String, Map<String, Task>> taskDetails = getTaskDetailsWithTaskKeys(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> statusData = entry.getValue();
if (statusData.containsKey(targetStatus)) {
matchedTasks.put(taskId, statusData);
}
}
return matchedTasks;
}
/**
* 根据任务ID获取所有状态数据
* @param taskId 任务ID
* @return 包含所有状态-数据的Map
*/
public Map<Object, Object> getAllTaskStatus(String taskId) {
String redisKey = CommonConstant.CMC_TASK_KEY_PREFIX + taskId;
try {
// 获取整个Hash,即该taskId下的所有状态和数据
return stringRedisTemplate.opsForHash().entries(redisKey);
} catch (RedisConnectionFailureException e) {
throw new RuntimeException("Redis连接失败", e);
} catch (Exception e) {
log.error("操作缓存异常:Key:{}", redisKey, e);
}
return null;
}
/**
* 删除整个任务数据
* @param taskId 任务ID
*/
public boolean deleteTask(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;
}
}